springboot+gradle集成redis实现动态存储值

的项目是使用的gradle构建的项目,项目使用redis实现共享缓存需要依赖项目jar包

//redis缓存
compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-redis', version: '1.3.5.RELEASE'
compile group: 'org.springframework.data', name: 'spring-data-redis', version: '1.7.2.RELEASE'





主配置文件application.properties添加一下内容

# Redis数据库索引(默认为0spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=600000

项目使用redis核心配置RedisConfiguration.java

package com.lxy.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig  extends CachingConfigurerSupport {
    /**
     * 管理缓存
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }
    @Bean
    public RedisTemplate, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
    {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate, Object> template = new RedisTemplate, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

 封装操作redis的工具 
  

package com.lxy.utils;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisClient {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final int DefaultTime = Integer.valueOf(PropertiesHander.getPropertiesValue("redis.cache.timeOut"));

    /**
     * 添加keyredis数据库中
     */
    public void set(String key, String value) throws Exception {
        ValueOperations, String> operations = redisTemplate.opsForValue();
        operations.set(key, value);
    }
    public void set(String key, String value,int timeOut) throws Exception {
        ValueOperations, String> operations = redisTemplate.opsForValue();
        int times = 0;
        if(timeOut>0){
            times = timeOut * 60;
        }else {
            times = DefaultTime;
        }
        operations.set(key, value, times, TimeUnit.SECONDS);
    }
    /**
     * 取值keyredis数据库中
     */
    public String get(String key) throws Exception  {
        ValueOperations, String> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }
    /**
     * 删除指定key
     */
     public void del(String key){
         redisTemplate.delete(key);
     }
    /**
     * 保存obj对象到redis数据库
     */
    public void setObj(Object obj){
        ValueOperations, Object> operations = redisTemplate.opsForValue();
        operations.set(obj.getClass().getName(),obj);
    }
    public void setObj(Object obj,int timeOut) throws Exception {
        ValueOperations, Object> operations = redisTemplate.opsForValue();
        int times = 0;
        if(timeOut>0){
            times = timeOut * 60;
        }else {
            times = DefaultTime;
        }
        operations.set(obj.getClass().getName(),obj, times, TimeUnit.SECONDS);
    }
    /**
     * 根据指定o获取Object
     */
    public <T> T getObj(Object obj,Class<T> clazz){

        ValueOperations, Object> operations = redisTemplate.opsForValue();
        return (T)operations.get(obj.getClass().getName());
    }

    /**
     * 删除obj对象在redis数据库
     */
    public void delObj(Object o){
        redisTemplate.delete(o);
    }
    /**
     * Set集合的赋值去取
     */
    public void setSetCollections(String key,Set value){
        redisTemplate.opsForSet().add(key,value);
    }
    public String getSetCollections(String key){
        String result = new Gson().toJson(redisTemplate.opsForSet().members(key));
        return result.substring(1,result.length()-1);
    }
    public Set getMapKeys(String key){
        SetresultMapSet=redisTemplate.opsForHash().keys(key);
        return resultMapSet;
    }

    /**
     * Map集合的赋值去取
     */
    public void setMapCollections(String key,Map,Object> value){
        redisTemplate.opsForHash().putAll(key,value);
    }
    public String getMapCollections(String key){
        return new Gson().toJson(redisTemplate.opsForHash().entries(key));
    }

    /**
     * List集合的赋值去取
     */
    public void setLists(String key,List list){
        redisTemplate.opsForList().leftPush(key, list);
    }

    public String getListStartEnd(String key,int start,int end){
        String result =new Gson().toJson(redisTemplate.opsForList().range(key, start, end));
        return result.substring(1,result.length()-1);
    }
    /**查询key的剩余存活时间*/
    public long getKeyExpireTime(String key){
        return  redisTemplate.getExpire(key);
    }

    /**设置key的剩余存活时间*/
    public boolean setKeyExpireTime(String key,int timeOut){
        long times = 0;
        if(timeOut>0){
            times = timeOut * 60;
        }else {
            times = DefaultTime;
        }
        return  redisTemplate.expire(key,times,TimeUnit.SECONDS);
    }
    /**判断key是否存在*/
    public boolean exitsKey(String key){
        Object obj = redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exists(key.getBytes());
            }
        });
        boolean flag=true;
        if (obj.toString().equals("false")){
            return false;
        }
        return flag;
    }
}
具体的测试接口

package com.lxy.controller;
import com.lxy.commons.Response;
import com.lxy.entity.User;
import com.lxy.utils.GsonUtils;
import com.lxy.utils.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;
@Controller
@RequestMapping({ "/redis" })
public class RedisController {

    @Autowired
    private RedisClient redisClinet;
    /**设置keyvalueredis*/
    @RequestMapping("/set")
    @ResponseBody
    public String set(String key, String value) throws Exception{
        redisClinet.set(key, value, 10);
        return "success";
    }
    /**根据key获取value*/
    @RequestMapping("/get")
    @ResponseBody
    public String get(String key) throws Exception {
        return redisClinet.get(key);
    }

    /**设置object对象到redis*/
    @RequestMapping("/setObj")
    @ResponseBody
    public String setObj(User user) throws Exception {
       redisClinet.setObj(user);
       return "success";
    }
    /**根据key获取Object对象*/
    @RequestMapping("/getObj")
    @ResponseBody
    public String getObj(User user) throws Exception {
        return GsonUtils.changeStr(redisClinet.getObj(user,User.class));
    }
    /**根据key获取set集合*/
    @RequestMapping("/setSet")
    @ResponseBody
    public String setSet(String key) throws Exception {
        Set set = new HashSet();
        set.add("a");
        set.add("b");
        set.add("c");
        redisClinet.setSetCollections(key,set);
        return "success";
    }

    /**根据key获取set集合*/
    @RequestMapping("/getSet")
    @ResponseBody
    public String getSet(String key) throws Exception {
        String resultStr = redisClinet.getSetCollections(key);
        List setList = GsonUtils.chanageList(resultStr, List.class);
        Set set = new HashSet(setList);
        return resultStr+"-------"+GsonUtils.changeStr(set);
    }
    /**设置map集合到redis*/
    @RequestMapping("/setMap")
    @ResponseBody
    public String setMap(String key) throws Exception {
        Map,Object> map = new HashMap,Object>();
        map.put("a","hanson");
        map.put("b","loly");
        map.put("c","zhangsan");
        redisClinet.setMapCollections(key,map);
        return "success";
    }
    /**根据key获取map集合*/
    @RequestMapping("/getMap")
    @ResponseBody
    public String getMap(String key) throws Exception {
        String resultStr = redisClinet.getMapCollections(key);
        Set keySets = redisClinet.getMapKeys(key);
        Map,Object> setList = GsonUtils.chanageList(resultStr, Map.class);

        return resultStr+"-------"+GsonUtils.changeStr(setList)+"---------"+GsonUtils.changeStr(keySets);
    }
    /**设置list集合到redis*/
    @RequestMapping("/setList")
    @ResponseBody
    public String setList(String key) throws Exception {
        List stringList = new ArrayList();
        stringList.add("d");
        stringList.add("e");
        stringList.add("f");
        redisClinet.setLists(key,stringList);
        return "success";
    }
    /**获取key对应的list集合*/
    @RequestMapping("/getList")
    @ResponseBody
    public String getList(String key) throws Exception {
        String resultStr = redisClinet.getListStartEnd(key,0,-1);
        List setList = GsonUtils.chanageList(resultStr, List.class);
        return resultStr+"------ ----"+GsonUtils.changeStr(setList);
    }
    /**删除key*/
    @RequestMapping("/del")
    @ResponseBody
    public String del(String key) throws Exception {
        redisClinet.del(key);
        return "被删除的key"+redisClinet.get(key);
    }
    @RequestMapping("/expire")
    @ResponseBody
    /**查询key的剩余存活时间*/
    public Response getKeyExpireTime(String key){
        long expireTime = redisClinet.getKeyExpireTime(key);
        return  Response.ok(200,key+"剩余存活时间:"+expireTime);
    }
    @RequestMapping("/exitsKey")
    @ResponseBody
    /**判断key是否存在*/
    public Response exitsKey(String key){
        boolean exitsFlag = redisClinet.exitsKey(key);
        return  Response.ok(200,key+"是否存在:"+exitsFlag);
    }

    @RequestMapping("/setKeyExpireTime")
    @ResponseBody
    /**判断key是否存在*/
    public Response setKeyExpireTime(String key,int time){
        long beforeExpireTime = redisClinet.getKeyExpireTime(key);
        redisClinet.setKeyExpireTime(key,time);
        long afterExpireTime = redisClinet.getKeyExpireTime(key);
        return  Response.ok(200,key+"设置之前剩余时间:"+beforeExpireTime+"----设置之后剩余时间:"+afterExpireTime);
    }
}

windows下安装redis客户端可参考:http://blog.csdn.net/zhousenshan/article/details/49127333

linux下安装redis可如下操作

参考网址:http://www.cnblogs.com/hanyinglong/p/5036558.html

下载地址:http://download.redis.io/releases/redis-3.0.5.tar.gz

提示下图信息证明redis的源码包已经下载成功

安装UnixTcl工具,如果不安装的话后期我们将无法对Redis进行测试,完成安装之后make test会报错

tcl包的下载地址是:http://downloads.sourceforge.net/tcl/tcl8.6.3-src.tar.gz

下载tcl成功的截图如下

centos下面安装gcc,我们使用yum(包管理器)安装,因为gcc依赖了很多东西,而有些包系统可能已经安装了,有些没有,所以下面的命令最后都执行一遍,在Xshell中执行下面的命令 每次中图确认是都输入Y

yuminstall cpp  

yuminstall binutils

yuminstall glibc-kernheaders

yuminstall glibc-common

yuminstall glibc-devel

yuminstall gcc

yuminstall make

备注:以上所有的包信息在安装完成的时候都会提示Complete,如果没有是Complete,而是Nothing to do,则说明服务器已经安装了这个包,不需要再次安装,所以没关系,继续执行下一个命令即可。

c.如果安装过程中没有报错,则说明gcc的安装已经完成了,下面继续安装tcl

 

将上传的tcl包解压,解压之后重命名为tcl,如图所示

tar -zxvf tcl8.6.3-src.tar.gz

mv tcl8.6.3 tcl

cd tcl 

d.解压完成之后使用下面的命令安装,命令执行顺序按照我写的即可。

cd unix/

 ./configure    

Make

make install

通过上面几步之后,准备工作已经完成,即可以开始安装redis了。

将上传的redis包解压,解压之后重命名为redis,如图所示:

tar -zxvf redis-3.0.5.tar.gz 

mv redis-3.0.5 redis

cd redis

当对包解压完成之后,便可以开始对其进行安装了,安装的命令为(redis目录下执行)

执行 make结果图如下

如果执行make出现错误,当再次执行make的话,我们建议,清理一下在执行,命令为:make clean

下面到 cd src/       make test 

make install

最后执行make install,不出现错误的话则说明redis安装成功,如图所示

当安装完redis之后,就需要进行测试,以下简单做一个测试来验证我们的redis是否安装成功。

首先我们启动redis服务,启动和关闭redis服务命令如下:

src/redis-server & 加上&表示使redis以后台程序方式运行

redis-server/usr/local/kencery/redis/redis.conf  启动redis

src/redis-cli shutdown    关闭redis

 输入启动redis的命令,启动redis,如图所示:

 redis启动完成之后,使用netstat -ntlp |grep 6379  查看端口是否在使用中,如果在使用中,则说明安装成功,否则安装没有成功。成功图如下

连接redis并且测试,连接命令为:src/redis-cli,最后的测试结果如图所示:

reids的安装和测试工作全部完成了

给文件添加权限,使用脚本文件可以执行,命令为:chmod755 /etc/init.d/redis

serviceredis start  开启redis服务

 serviceredis stop 关闭redis服务

 

首先设置redis.config中的daemonizeyes,确保守护进行开启,执行以下命令:

 vim redis.conf  开启配置文件,找到daemonize属性酒设置为yes保存并且退出即可。

然后设置开机启动,命令:chkconfig redis on

开机自启动可按照设定即可   http://blog.csdn.net/liqi_q/article/details/78042882

你可能感兴趣的:(springboot+gradle集成redis实现动态存储值)