赞
踩
上一文我们介绍了响应式编程/反应式编程到底是什么,通过案例连接了Redis,但是我们的操作都是返回 Mono 或者 Flux,那么很多小伙伴不习惯这种方式,所以本文就是一个比较贴合之前我们使用Jedis 连接 Redis ,只不过换成了Lettuce。
当你看到我这篇文章的时候我想你不是第一次查找怎么使用Lettuce 连接Redis 吧,可能我写的Demo无法满足你们项目需求,那就取各文章的优点综合考虑你的个性化配置,可以加微信探讨,最下方。
Spring Boot2.x 不再使用Jedis,换成了Lettuce。Lettuce是基于 Netty 实现的,所以性能更好。
使用所有框架和中间件的版本
框架 | 版本 |
Spring Boot | 2.1.3.RELEASE |
redis | redis-4.0.11 |
JDK | 1.8.x |
我们还是使用上篇文章的工程
pom 修改成
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-pool2</artifactId>
- <version>2.5.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.6</version>
- </dependency>
Redis配置类
由于我们Demo求简,所以一切配置尽量使用默认,所以我没做集群,也没写配置文件,只对 RedisTemplate 进行了序列化。
- @Configuration
- @AutoConfigureAfter(RedisAutoConfiguration.class)
- public class RedisCacheAutoConfiguration {
- @Bean
- public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
- RedisTemplate<String, Serializable> template = new RedisTemplate<>();
- template.setKeySerializer(new StringRedisSerializer());
- template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
- template.setConnectionFactory(redisConnectionFactory);
- return template;
- }
-
- }
启动类及测试
- @SpringBootApplication
- public class RedisDemoApplication implements ApplicationRunner {
- @Autowired
- private RedisTemplate<String, Serializable> redisCacheTemplate;
-
-
-
- public static void main(String[] args) {
- SpringApplication.run(RedisDemoApplication.class, args);
- }
-
-
-
- @Override
- public void run(ApplicationArguments args) throws Exception {
-
- redisCacheTemplate.opsForHash().put("apple", "x", "6000");
- redisCacheTemplate.opsForHash().put("apple", "xr", "5000");
- redisCacheTemplate.opsForHash().put("apple", "xs max","8000");
-
- System.out.print(redisCacheTemplate.opsForHash().get("apple", "xs max"));
- }
- }
启动测试类
输出如下
更多配置点击,这是一个简书上访问量比较高的一篇。
https://www.jianshu.com/p/feef1421ab0b
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。