Spring Boot中使用Lettuce连接Redis

该博客介绍了如何在Spring Boot中使用Lettuce连接Redis,首先简述了Redis的安装和启动,然后详细说明了Spring Boot集成Lettuce的过程,包括Maven引入、配置文件设置、Redis配置类的编写,并提供了测试类的示例,最后提到了使用Redis的注意事项,如实现Serializable接口和使用@Resource注解。

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

一、Redis的使用

关于Redis的使用和介绍,可以查看Redis中文网

1、使用Docker安装
Docker Hub中搜索Redis,获得镜像的安装方式

docker pull redis

docker默认安装最新版本(latest),如果需要选择版本,为:镜像名称:<版本号>,例如:

docker pull redis:5.0.5

2、启动
使用命令docker images查看已安装镜像
在这里插入图片描述
启动Redis 镜像

docker run redis -d --name myredis -p 6379:6379
  • redis 表示镜像名称,对应上图中的REPOSITORY字段
  • -d 表示后台运行
  • –name 设置容器的名称,方便使用docker ps进行管理
  • -p 端口映射

使用docker ps 查看当前运行镜像,可以发现Redis 镜像已启动:
在这里插入图片描述

二、Spring Boot 使用Redis

Lettuce 和 Jedis 的定位都是Redis 的client,所以他们当然可以直接连接redis server。
Jedis 在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接。
Lettuce 的连接是基于Netty 的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection 是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

以上介绍来自知乎

1、Maven 引入
Spring Boot2.0之后默认使用Lettuce 作为客户端来连接Redis 服务器,本文选择Lettuce

	<!-- Redis -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
	<!-- Lettuce -->
	<dependency>
		<groupId>io.lettuce</groupId>
		<artifactId>lettuce-core</artifactId>
	</dependency>

2、配置文件

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

3、Redis 配置类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
	
	@Value("${spring.redis.host}")
	private String host;

	@Value("${spring.redis.port}")
	private int port;

	@Value("${spring.redis.password}")
	private String password;
	
	// 缓存管理器 设置Redis为缓存
	@Bean
	public CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
		RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
				.fromConnectionFactory(lettuceConnectionFactory);
		return builder.build();
	}
	
	/*
	 * Redis 连接工厂
	 */
	@Bean
	public LettuceConnectionFactory redisConnectionFactory() {
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName(host);
		redisStandaloneConfiguration.setPort(port);
		if (StringUtils.isNotBlank(password)) {
			redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
		}
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
	
	@Bean
	public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		// key序列化,采用StringRedisSerializer
		redisTemplate.setKeySerializer(redisSerializer);
		redisTemplate.setHashKeySerializer(redisSerializer);
		// value序列化,采用jackson2JsonRedisSerializer
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
		return redisTemplate;
	}
	
	@Bean
	public StringRedisTemplate stringRedisTempalte(LettuceConnectionFactory lettuceConnectionFactory) {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(lettuceConnectionFactory);
		return stringRedisTemplate;
	}
	
}

4、Redis的使用及注意事项
编写测试类:

	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	@Test
	public void redisTest() {
		redisTemplate.opsForValue().set("redisTest", "RedisTest");
	}
	
	@Test
	public void userTest() {
		User user = new User();
		user.setName("SpringBoot");
		user.setAge(1);
		redisTemplate.opsForValue().set("user", user);
	}

运行,使用Redis Desktop Manager连接Redis,查看结果:
在这里插入图片描述

数据存储成功。
注意事项:
1、使用Redis存储一个类时,这个类需实现Serializable 接口,否则程序会报错。
2、使用RedisTemplate<k, v>时,需要使用@Resource,而不是@Autowired。原因可查看SpringBoot文档:

If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值