1. 为什么需要 Redis 缓存?
在传统的单体架构中,所有请求直接打到数据库(MySQL)。当并发量上升时,数据库会成为整个系统的瓶颈。引入 Redis 缓存可以:
降低响应耗时:内存读取速度远超磁盘。
减轻数据库压力:热点数据由缓存承载。
提高并发能力:支持每秒数万次的请求。
2. 环境准备
JDK: 1.8+
Spring Boot: 2.7.x / 3.x
Redis: 5.0+ (本地或 Docker 运行均可)
3. 实战步骤
第一步:引入依赖
在pom.xml中添加 Spring Data Redis 依赖:
XML
<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>第二步:核心配置
在application.yml中配置 Redis 连接信息:
YAML
spring: redis: host: 127.0.0.1 port: 6379 password: # 如果有密码请填写 lettuce: pool: max-active: 8 # 最大连接数 max-idle: 8 # 最大空闲连接第三步:编写自定义 RedisTemplate
默认的RedisTemplate会导致 Key 出现乱码(二进制格式),我们需要配置 JSON 序列化:
Java
@Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 设置 Key 为 String 序列化 template.setKeySerializer(new StringRedisSerializer()); // 设置 Value 为 JSON 序列化 template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } }第四步:业务代码实战(以查询用户信息为例)
采用经典的“Cache Aside Pattern”(旁路缓存)模式:
Java
@Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private UserMapper userMapper; public User getUserById(Long id) { String key = "user:" + id; // 1. 先从 Redis 查询 User user = (User) redisTemplate.opsForValue().get(key); if (user != null) { System.out.println("--- 缓存命中 ---"); return user; } // 2. 缓存未命中,查询数据库 System.out.println("--- 缓存未命中,查询数据库 ---"); user = userMapper.selectById(id); // 3. 将结果写入缓存,设置过期时间(防止雪崩) if (user != null) { redisTemplate.opsForValue().set(key, user, 30, TimeUnit.MINUTES); } return user; } }4. 实战进阶:使用@Cacheable注解
如果你不想手动写redisTemplate,可以使用 Spring 提供的注解:
Java
@Service public class ProductService { // value: 缓存名, key: 缓存键, unless: 结果为 null 时不缓存 @Cacheable(value = "products", key = "#id", unless = "#result == null") public Product getProduct(Long id) { return productMapper.findById(id); } }5. 避坑指南(生产必备)
缓存击穿:热点 Key 过期瞬间,大量请求涌入 DB。解决:设置热点数据永不过期或加锁。
缓存雪崩:大量 Key 同时过期。解决:在过期时间上加一个随机偏移量。
序列化问题:如果你的实体类没有
Serializable接口,或者没有无参构造函数,Redis 会报错。
6. 总结
通过本文,我们实现了在 Spring Boot 中集成 Redis,并掌握了手动操作和注解操作两种方式。缓存是一把双刃剑,使用时一定要注意数据一致性和过期策略。
源码仓库:github.com/yourname/redis-demo (此处可替换为你自己的仓库)
如果你觉得这篇文章对你有帮助,请点赞、收藏、关注!我是TechExplorer(技术探索者)
带你玩转实战开发。