SpringBoot2.2.x(十五)整合Redis

本系列文章都是基于SpringBoot2.2.5.RELEASE

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置文件

spring.redis.host=localhost
spring.redis.port=6379

用法

SpringBoot为我们提供了两个操作Redis数据库的模板

  1. RedisTemplate,key和value可以是任意的数据类型。
  2. StringRedisTemplate,key和value只能是String类型的。

下面以StringRedisTemplate为例

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTemplateTests {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 1. 操作字符串
    @Test
    public void test1() {
        // 设置key-value
        stringRedisTemplate.opsForValue().set("key1","value1");
        // 为key设置过期时间
        stringRedisTemplate.expire("key1",10,TimeUnit.SECONDS);
        
        // 上面的两条语句可以写成一条
        // 设置key-value并设置过期时间
        stringRedisTemplate.opsForValue().set("key1","value1",10,TimeUnit.SECONDS);
        
        // 通过key来获取value
        stringRedisTemplate.opsForValue().get("key1")
    }
    
    // 2. 操作List
    @Test
    public void test2() {
        stringRedisTemplate.opsForList().rightPush("key1","value1");
        stringRedisTemplate.opsForList().rightPush("key1","value2");
        stringRedisTemplate.opsForList().rightPush("key1","value3");

        // 使用range获取整个list数据
        List<String> values = stringRedisTemplate.opsForList().range("key1", 0, -1);
        values.stream().forEach(s -> System.out.println(s));
    }
    
    // 剩下的set、zset、hash用法也是类似的
}

自动配置

使用了上面的依赖后,由于SpringBoot的自动装配功能,它会自动地帮我们创建好RedisConnectionFactory

我们也可以自定义创建RedisConnectionFactory,如下所示

@Configuration
public class RedisConfig {
    @Bean
    RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration =
                new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("localhost");
//        redisStandaloneConfiguration.setDatabase(0);
//        redisStandaloneConfiguration.setPassword("xxxxxx");
        redisStandaloneConfiguration.setPort(6379);
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
}

查看Redis自动配置类RedisAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}
    
	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}
}

可以发现,SpringData Redis为我们提供了两个操作Redis数据库的模板

  1. RedisTemplate
  2. StringRedisTemplate

RedisTemplate可以极大地简化了Redis数据访问,能够让我们持久化各种类型的key和value,并不局限于字节数组。StringRedisTemplate继承了RedisTemplate,只关注key和value都是String类型的

key和value的序列化器

当某个条目保存到Redis key-value存储的时候,key和value都会使用Redis的序列化器。Spring Data Redis提供了多个这样的序列化器,如下所示

  • GenericToStringSerializer:使用String转换服务进行序列化
  • Jackson2JsonRedisSerializer:使用Jackson2将对象序列化成JSON
  • JdkSerializationRedisSerializer:使用Java序列化

查看RedisTemplate类里面的afterPropertiesSet方法可以知道,RedisTemplate默认使用的是JdkSerializationRedisSerializer,这意味着key和value都会通过Java进行序列化。

查看StringRedisTemplate的无参构造函数可以发现,StringRedisTemplate默认使用的是StringRedisSerializer,它实际上就是实现String与byte数组之间的相互转换。

假设我们使用RedisTemplate的时候,我们希望key是String类型的,value为Object类型,希望将value序列化为JSON,那么RedisTemplate的setKeySerializer()方法和setValueSerializer()方法需要如下所示:

@Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        // 这里使用的是阿里巴巴的fastjson
        template.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值