Redis作为高性能的键值存储数据库,在缓存、会话管理、排行榜等场景中被广泛应用。Spring Boot通过Spring Data Redis
提供了与Redis的无缝整合能力,使开发者能够快速实现高效的数据缓存与存储。本文将手把手教你如何在Spring Boot项目中整合Redis,并通过实际案例展示其核心用法。
# 拉取Redis镜像
docker pull redis
# 启动Redis容器
docker run -d --name my-redis -p 6379:6379 redis
sudo apt-get install redis-server
sudo systemctl start redis
使用 Spring Initializr 创建项目,勾选以下依赖:
检查pom.xml
中是否包含Redis依赖:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
在application.properties
中添加配置:
# Redis基础配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password= # 若无密码则留空
# 连接池配置(可选)
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=1000ms
Spring Boot已自动配置RedisTemplate
,可直接注入使用:
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 写入数据
redisTemplate.opsForValue().set("user:1:name", "John");
// 读取数据
String userName = (String) redisTemplate.opsForValue().get("user:1:name");
System.out.println("用户名:" + userName); // 输出:John
// 定义用户对象
@Data
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
}
// 存储Hash
User user = new User(1L, "Alice", 25);
redisTemplate.opsForHash().put("user:1", "info", user);
// 读取Hash
User cachedUser = (User) redisTemplate.opsForHash().get("user:1", "info");
System.out.println("用户年龄:" + cachedUser.getAge()); // 输出:25
Spring Cache支持通过注解自动缓存数据:
// 启用缓存
@SpringBootApplication
@EnableCaching
public class DemoApplication { ... }
// 在Service层使用缓存
@Service
public class UserService {
@Cacheable(value = "userCache", key = "#id")
public User getUserById(Long id) {
// 模拟数据库查询
System.out.println("查询数据库...");
return new User(id, "Tom", 30);
}
}
@Cacheable
: 方法结果会被缓存,后续调用直接返回缓存值。@CacheEvict
: 删除缓存项。默认的JDK序列化可读性差,建议改为JSON格式:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson2JsonRedisSerializer序列化
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(om);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
return template;
}
}
public boolean tryLock(String lockKey, String requestId, long expireTime) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
}
public boolean releaseLock(String lockKey, String requestId) {
String currentId = (String) redisTemplate.opsForValue().get(lockKey);
if (requestId.equals(currentId)) {
redisTemplate.delete(lockKey);
return true;
}
return false;
}
RedisConnectionFailureException: Unable to connect to Redis
Could not read JSON: Unrecognized field
@JsonIgnore
)。@Cacheable(value = "userCache", key = "#id", unless = "#result == null")
public User getUserById(Long id) { ... }