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<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
    {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, Object> template = new RedisTemplate<String, 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, String> operations = redisTemplate.opsForValue();
        operations.set(key, value);
    }
    public void set(String key, String value,int timeOut) throws Exception {
        ValueOperations<String, 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, 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, Object> operations = redisTemplate.opsForValue();
        operations.set(obj.getClass().getName(),obj);
    }
    public void setObj(Object obj,int timeOut) throws Exception {
        ValueOperations<Object, 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, 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<String> getMapKeys(String key){
        Set<String>resultMapSet=redisTemplate.opsForHash().keys(key);
        return resultMapSet;
    }

    /**
     * Map集合的赋值去取
     */
    public void setMapCollections(String key,Map<String,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<String> set = new HashSet<String>();
        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<String> setList = GsonUtils.chanageList(resultStr, List.class);
        Set<String> set = new HashSet<String>(setList);
        return resultStr+"-------"+GsonUtils.changeStr(set);
    }
    /**设置map集合到redis*/
    @RequestMapping("/setMap")
    @ResponseBody
    public String setMap(String key) throws Exception {
        Map<String,Object> map = new HashMap<String,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<String> keySets = redisClinet.getMapKeys(key);
        Map<String,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<String> stringList = new ArrayList<String>();
        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<String> 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


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,我可以给你一些关于在 Spring Boot 中使用 Redis 的指导。 首先,你需要在你的项目中添加对 Redis 的依赖。在你的 `build.gradle` 文件中添加如下依赖: ``` compile 'org.springframework.boot:spring-boot-starter-data-redis' ``` 然后,在你的配置文件中(例如 `application.properties`)中添加 Redis 的连接信息: ``` # Redis configuration spring.redis.host=localhost spring.redis.port=6379 ``` 接下来,你需要创建一个 RedisTemplate 和一个 StringRedisTemplate,用来对 Redis 进行操作。你可以在你的配置类中创建这两个 Bean。 ``` @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } ``` 最后,你就可以在你的代码中使用这两个 Bean 来对 Redis 进行操作了。例如: ``` @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } ``` 希望这些内容能对你有帮助。 ### 回答2: Spring Boot中使用Redis可以通过两个步骤来实现。 第一步是引入Redis的依赖。在pom.xml文件中添加以下依赖项以使用Redis: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 第二步是配置Redis连接属性。在application.properties(或application.yml)文件中添加以下属性: ``` spring.redis.host=hostname spring.redis.port=port spring.redis.password=password ``` 其中,`hostname`是Redis服务器的主机名,`port`是Redis服务器的端口号,`password`是Redis服务器的密码(如果有密码的话)。 配置完成后,就可以在Spring Boot的应用程序中使用Redis了。可以使用`@Autowired`注解将`RedisTemplate`或`StringRedisTemplate`注入到需要使用Redis的类中。例如: ```java @Service public class UserService { @Autowired private StringRedisTemplate stringRedisTemplate; public void saveUser(String id, String name) { stringRedisTemplate.opsForValue().set(id, name); } public String getUser(String id) { return stringRedisTemplate.opsForValue().get(id); } } ``` 上述示例中,`StringRedisTemplate`是通过依赖注入得到的,可以使用其提供的`opsForValue()`方法来操作Redis的字符串。 通过以上步骤,就可以在Spring Boot应用程序中使用Redis进行数据存储和检索了。 ### 回答3: Spring Boot是一个开源的Java框架,可以轻松创建独立的、生产级别的Spring应用程序。在Spring Boot中使用Redis,可以提供高性能的缓存和数据存储解决方案。 首先,我们需要在项目的pom.xml文件中添加Redis相关的依赖项。可以使用Spring Boot的starters来简化这个过程,只需添加以下依赖即可: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,我们需要在application.properties或application.yaml文件中配置Redis连接。以下是一个示例配置: ``` spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=123456 ``` 其中,host表示Redis服务器的主机名,port表示端口号,password表示连接密码(如果有的话)。 接着,我们可以在Spring Boot应用程序中使用RedisTemplate或者注解来访问Redis。例如,我们可以使用注解@Autowired将RedisTemplate注入到我们的服务或控制器中: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; ``` 然后,我们可以使用redisTemplate来执行各种操作,比如存储和检索数据: ``` redisTemplate.opsForValue().set("key", "value"); String value = (String) redisTemplate.opsForValue().get("key"); ``` 另外,我们还可以使用Spring Boot的缓存注解简化对Redis的访问。通过在方法上添加@Cacheable、@CachePut或@CacheEvict等注解,可以自动将方法的结果存储Redis缓存中。 总之,Spring Boot提供了简单方便的集成Redis的方式,我们可以通过配置文件或者注解的方式来使用Redis,从而提升应用程序的性能和扩展性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值