前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot2.0 使用Lettuce 连接Redis

Spring Boot2.0 使用Lettuce 连接Redis

作者头像
胖虎
发布2019-06-26 17:16:24
1.6K0
发布2019-06-26 17:16:24
举报
文章被收录于专栏:晏霖晏霖
前言

上一文我们介绍了响应式编程/反应式编程到底是什么,通过案例连接了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 修改成

代码语言:javascript
复制
<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 进行了序列化。

代码语言:javascript
复制
@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;
    }

}

启动类及测试

代码语言:javascript
复制
@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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 晏霖 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 正文
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档