Spring Boot2.0 使用Lettuce 连接Redis

本文详细介绍如何在SpringBoot 2.x中使用Lettuce替代Jedis连接Redis,包括环境配置、依赖引入、序列化设置及简单操作示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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

<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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值