当前位置:   article > 正文

Spring Boot2.0 使用Lettuce 连接Redis_springboot 2 lettuce 连接redis 集群(代理模式)

springboot 2 lettuce 连接redis 集群(代理模式)

前言

上一文我们介绍了响应式编程/反应式编程到底是什么,通过案例连接了Redis,但是我们的操作都是返回 Mono 或者 Flux,那么很多小伙伴不习惯这种方式,所以本文就是一个比较贴合之前我们使用Jedis 连接 Redis ,只不过换成了Lettuce。

当你看到我这篇文章的时候我想你不是第一次查找怎么使用Lettuce 连接Redis 吧,可能我写的Demo无法满足你们项目需求,那就取各文章的优点综合考虑你的个性化配置,可以加微信探讨,最下方。

正文

Spring Boot2.x 不再使用Jedis,换成了Lettuce。Lettuce是基于 Netty 实现的,所以性能更好。

 

使用所有框架和中间件的版本

环境
框架版本
Spring Boot                2.1.3.RELEASE
redisredis-4.0.11
JDK1.8.x

 

我们还是使用上篇文章的工程

pom 修改成

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.apache.commons</groupId>
  7. <artifactId>commons-pool2</artifactId>
  8. <version>2.5.0</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>com.fasterxml.jackson.core</groupId>
  12. <artifactId>jackson-databind</artifactId>
  13. <version>2.9.6</version>
  14. </dependency>

 

Redis配置类

由于我们Demo求简,所以一切配置尽量使用默认,所以我没做集群,也没写配置文件,只对 RedisTemplate 进行了序列化。

  1. @Configuration
  2. @AutoConfigureAfter(RedisAutoConfiguration.class)
  3. public class RedisCacheAutoConfiguration {
  4. @Bean
  5. public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
  6. RedisTemplate<String, Serializable> template = new RedisTemplate<>();
  7. template.setKeySerializer(new StringRedisSerializer());
  8. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  9. template.setConnectionFactory(redisConnectionFactory);
  10. return template;
  11. }
  12. }

 

启动类及测试

  1. @SpringBootApplication
  2. public class RedisDemoApplication implements ApplicationRunner {
  3. @Autowired
  4. private RedisTemplate<String, Serializable> redisCacheTemplate;
  5. public static void main(String[] args) {
  6. SpringApplication.run(RedisDemoApplication.class, args);
  7. }
  8. @Override
  9. public void run(ApplicationArguments args) throws Exception {
  10. redisCacheTemplate.opsForHash().put("apple", "x", "6000");
  11. redisCacheTemplate.opsForHash().put("apple", "xr", "5000");
  12. redisCacheTemplate.opsForHash().put("apple", "xs max","8000");
  13. System.out.print(redisCacheTemplate.opsForHash().get("apple", "xs max"));
  14. }
  15. }

 

 启动测试类

输出如下

更多配置点击,这是一个简书上访问量比较高的一篇。

https://www.jianshu.com/p/feef1421ab0b

 

 

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号