SpringBoot程序员Spring-Boot

Springboot整合redis

2017-09-24  本文已影响6533人  阿卧

springboot提供了spring-data-redis的框架来整合redis的操作。下面主要介绍,springboot整合redis的配置,以及spring-data-redis是如何提供便捷的操作来处理redis。

  1. redis环境准备

在使用redis之前需要先安装redis数据库,具体的安装流程可以参考
http://blog.csdn.net/u011521890/article/details/54175233

  1. redis知识技能

同时,要了解redis自身的知识体系,基本的key、map、list等的操作命令。这个可以参考
http://www.runoob.com/redis/redis-hashes.html

  1. springboot的环境

使用maven在pom文件中导入springboot的依赖(这里提供一个demo,欢迎star)。
https://github.com/hpulzl/book_recommend

redis的环境依赖

注意spring-boot-starter-data-redis与springboot版本的问题。

我项目中使用的springboot版本是1.3.8,

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.8.RELEASE</version>
  </parent>

但是spring-boot-starter-data-redis只有1.4版本以上的。所以要指定spring-boot-starter-data-redis的version版本。

<!--添加redis缓存依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <version>1.5.0.RELEASE</version>
    </dependency>

redis配置文件

在application.properties文件中写下连接redis所需要的信息。

# Redis数据库索引(默认为0),如果设置为1,那么存入的key-value都存放在select 1中
spring.redis.database=0 
# Redis服务器地址
spring.redis.host=localhost
# 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=0

RedisCacheConfig配置

主要分3个步骤

RedisSerializer redis序列化的接口类
OxmSerializer xml到object的序列化/反序列化
StringRedisSerializer string字符串的序列化/反序列化
JacksonJsonRedisSerializer json到object的序列化/反序列化
Jackson2JsonRedisSerializer json到object的序列化/反序列化
JdkSerializationRedisSerializer java对象的序列化/反序列化

从源码看,RedisTemplate默认使用的是JdkSerializationRedisSerializer。我的项目中选择Jackson2JsonRedisSerializer的序列化器
此时,需要引入Jackson的依赖

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.7</version>
    </dependency>
@Configuration
@EnableAutoConfiguration
public class RedisCacheConfig extends CachingConfigurerSupport {
    
    @Value("${spring.redis.host}")
    private String host;
    
    @Value("${spring.redis.port}")
    private int port;
    
    @Value("${spring.redis.timeout}")
    private int timeout;
    
    @Value("${spring.redis.database}")
    private int database;
    
    @Value("${spring.redis.password}")
    private String password;

    /**
     * 连接redis的工厂类
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout);
        factory.setPassword(password);
        factory.setDatabase(database);
        return factory;
    }

    /**
     * 配置RedisTemplate
     * 设置添加序列化器
     * key 使用string序列化器
     * value 使用Json序列化器
     * 还有一种简答的设置方式,改变defaultSerializer对象的实现。
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        //StringRedisTemplate的构造方法中默认设置了stringSerializer
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //set key serializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //set value serializer
        template.setDefaultSerializer(jackson2JsonRedisSerializer);

        template.setConnectionFactory(jedisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }
}

以上完成后,环境配置基本完成,接下来需要验证springboot与redis是否整合成功。

  1. 启动redis服务
./redis-s/redis-server 

控制台出现这个画面,说明启动成功!


这里写图片描述
  1. 写一个testCase实例验证
 @Autowired
 private RedisTemplate<String,Object> redisTemplate;
    
@Test
public void stringTest(){
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("hello", "redis");
        System.out.println("useRedisDao = " + valueOperations.get("hello"));
    }

结果如下所示,并且redis缓存中存储的是json的格式。
如果我们存入一个对象,那个这个对象也将是json的格式。


这里写图片描述

需要注意的地方
第一次配置redis的时候,application.properties文件设置

spring.redis.database=2

说明使用的redis数据库为2,那么需要将redis切换到数据库2的目录中才能看到redis的值
在redis客户端使用如下命令

select 2
这里写图片描述

然后再进行redis的操作。

SDR(spring-data-redis)的官方讲解如下
https://docs.spring.io/spring-data/redis/docs/1.8.1.RELEASE/reference/html/#redis:template

上一篇 下一篇

猜你喜欢

热点阅读