Spring Boot集成Redis:从配置到实战的完整指南
Redis作为高性能的内存数据库,在现代应用开发中扮演着至关重要的角色。本文将详细讲解如何在Spring
Boot项目中集成Redis,并提供多种使用场景的实战代码。
一、为什么需要集成Redis?
Redis在Spring Boot应用中的核心价值:
-
性能加速:将热点数据存入内存,访问速度比数据库快100倍
-
解耦应用:作为独立的缓存层,减轻数据库压力
-
丰富数据结构:支持字符串、哈希、列表、集合等高级数据结构
-
分布式支持:实现分布式锁、会话共享等功能
-
消息系统:提供发布/订阅模式实现异步通信
二、环境准备
-
JDK 17+
-
Spring Boot 3.2.0+
-
Redis 7.0+
三、快速集成Redis
1. 添加依赖
在pom.xml中添加Spring Data Redis和连接池依赖:
xml
<dependencies>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- JSON序列化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
2. 配置Redis连接
在application.yml中添加配置:
yaml
spring:
redis:
host: 127.0.0.1
port: 6379
password: yourpassword # 无密码可省略
database: 0 # 默认DB
lettuce:
pool:
max-active: 20 # 最大连接数
max-idle: 10 # 最大空闲连接
min-idle: 5 # 最小空闲连接
max-wait: 2000ms # 获取连接最大等待时间
3. 配置RedisTemplate
创建配置类解决键值序列化问题:
java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 使用Jackson序列化value
Jackson2JsonRedisSerializer<Object> serializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(
mapper.getPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL
);
serializer.setObjectMapper(mapper);
// 设置序列化
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
四、Redis基础操作实战
1. 使用RedisTemplate操作
java
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 字符串操作
public void setString(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String getString(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
// 哈希操作
public void setHash(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
public Object getHash(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
// 设置过期时间
public void setWithExpire(String key, Object value, long seconds) {
redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
}
// 删除键
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
}
2. 测试Controller
java
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisService redisService;
@PostMapping("/set")
public String setValue(@RequestParam String key,
@RequestParam String value) {
redisService.setString(key, value);
return "设置成功: " + key + "=" + value;
}
@GetMapping("/get/{key}")
public String getValue(@PathVariable String key) {
return "获取结果: " + redisService.getString(key);
}
@PostMapping("/setUser")
public String setUser(@RequestParam String userId) {
User user = new User(userId, "用户" + userId, "user" + userId + "@example.com");
redisService.setHash("user:" + userId, "profile", user);
return "用户信息已缓存";
}
@GetMapping("/getUser/{userId}")
public User getUser(@PathVariable String userId) {
return (User) redisService.getHash("user:" + userId, "profile");
}
// 用户实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
static class User implements Serializable {
private String id;
private String name;
private String email;
}
}
五、Spring Cache集成Redis
1. 启用缓存支持
在启动类添加注解:
java
@SpringBootApplication
@EnableCaching // 启用缓存功能
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
2. 配置缓存管理器
java
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Autowired
private RedisConnectionFactory connectionFactory;
@Bean
public CacheManager cacheManager() {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30)) // 默认过期时间
.disableCachingNullValues() // 不缓存null
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
}
}
3. 使用缓存注解
java
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProductById(String id) {
// 模拟数据库查询
System.out.println("查询数据库: " + id);
return new Product(id, "商品" + id, 99.99);
}
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
// 模拟数据库更新
System.out.println("更新数据库: " + product.getId());
return product;
}
@CacheEvict(value = "products", key = "#id")
public void deleteProduct(String id) {
System.out.println("删除数据库记录: " + id);
}
// 条件缓存:只缓存价格大于100的商品
@Cacheable(value = "expensiveProducts", key = "#id", condition = "#result.price > 100")
public Product getProductWithCondition(String id) {
return new Product(id, "高级商品", 199.99);
}
}