JeecgBoot缓存策略:Redis分布式缓存配置与使用
引言
在企业级应用开发中,缓存技术是提升系统性能的关键手段。JeecgBoot作为一款优秀的企业级低代码开发平台,深度集成了Redis分布式缓存,为开发者提供了完善的缓存解决方案。本文将深入解析JeecgBoot的Redis缓存策略,从配置到使用,帮助开发者掌握这一重要技术。
Redis缓存架构设计
整体架构概览
JeecgBoot采用Spring Boot + Spring Cache + Redis的技术栈构建缓存体系,其架构设计如下:
核心组件说明
| 组件 | 职责 | 实现类 |
|---|---|---|
| CacheManager | 缓存管理器 | RedisCacheManager |
| RedisTemplate | Redis操作模板 | RedisTemplate<String, Object> |
| Key生成器 | 缓存键生成 | SimpleKeyGenerator |
| 序列化器 | 数据序列化 | Jackson2JsonRedisSerializer |
Redis配置详解
基础配置
在JeecgBoot中,Redis配置主要通过application.yml文件进行管理:
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
timeout: 3000ms
lettuce:
pool:
max-active: 20
max-wait: -1ms
max-idle: 10
min-idle: 0
高级配置选项
spring:
cache:
type: redis
redis:
time-to-live: 3600000 # 缓存过期时间(毫秒)
cache-null-values: true # 是否缓存空值
key-prefix: 'jeecg:' # 缓存键前缀
use-key-prefix: true # 是否使用键前缀
缓存注解使用指南
@Cacheable - 数据缓存
@Cacheable(value = CacheConstant.SYS_DICT_CACHE, key = "#code", unless = "#result == null")
public SysDict getDictByCode(String code) {
return baseMapper.selectOne(new LambdaQueryWrapper<SysDict>()
.eq(SysDict::getDictCode, code));
}
参数说明:
value: 缓存名称,对应CacheConstant中定义的常量key: SpEL表达式,用于生成缓存键unless: 条件表达式,满足条件时不缓存
@CacheEvict - 缓存清除
@CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries = true)
public void updateDict(SysDict dict) {
baseMapper.updateById(dict);
}
清除策略:
allEntries = true: 清除该缓存名称下的所有条目key: 指定清除特定键的缓存
@CachePut - 更新缓存
@CachePut(value = CacheConstant.SYS_USERS_CACHE, key = "#user.username")
public SysUser updateUser(SysUser user) {
baseMapper.updateById(user);
return user;
}
缓存常量定义
JeecgBoot定义了丰富的缓存常量,确保缓存键的统一管理:
| 缓存常量 | 描述 | 使用场景 |
|---|---|---|
| SYS_DICT_CACHE | 数据字典缓存 | 字典数据查询 |
| SYS_USERS_CACHE | 用户信息缓存 | 用户登录、信息查询 |
| SYS_DEPARTS_CACHE | 部门信息缓存 | 组织架构查询 |
| GATEWAY_ROUTES | 网关路由缓存 | 动态路由配置 |
| SYS_DATA_PERMISSIONS_CACHE | 数据权限缓存 | 权限控制 |
分布式缓存实战
1. 用户登录缓存
@Cacheable(cacheNames = CacheConstant.SYS_USERS_CACHE, key = "#username")
public SysUser getUserByUsername(String username) {
return baseMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getUsername, username));
}
2. 数据字典缓存
@Cacheable(value = CacheConstant.SYS_DICT_CACHE, key = "#code+':'+#key", unless = "#result == null")
public String getDictItemText(String code, String key) {
// 查询字典项文本逻辑
}
3. 网关路由缓存
public void addRoute2Redis(String key) {
List<GatewayRoute> routes = list();
redisTemplate.opsForValue().set(key, routes);
}
缓存监控与管理
Redis监控端点
JeecgBoot提供了完善的Redis监控功能:
@RestController
@RequestMapping("/sys/actuator/redis")
public class ActuatorRedisController {
@Autowired
private RedisService redisService;
@GetMapping("/info")
public Result<?> getRedisInfo() throws Exception {
List<RedisInfo> infoList = this.redisService.getRedisInfo();
return Result.ok(infoList);
}
}
监控指标
监控端点提供以下关键指标:
- Redis服务器版本信息
- 内存使用情况
- 连接数统计
- 命令处理数量
- 网络流量监控
性能优化策略
1. 缓存穿透防护
@Cacheable(value = "user_cache", key = "#id",
unless = "#result == null",
condition = "#id != null")
public User getUserById(Long id) {
User user = userMapper.selectById(id);
if (user == null) {
// 缓存空值,防止穿透
return new User();
}
return user;
}
2. 缓存雪崩预防
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30)) // 设置过期时间
.disableCachingNullValues() // 不缓存空值
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new Jackson2JsonRedisSerializer<>(Object.class)));
// 为不同缓存设置不同的过期时间
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
cacheConfigurations.put("short_term", config.entryTtl(Duration.ofMinutes(5)));
cacheConfigurations.put("long_term", config.entryTtl(Duration.ofHours(2)));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.withInitialCacheConfigurations(cacheConfigurations)
.build();
}
3. 热点数据缓存
@Cacheable(value = "hot_data", key = "#key",
sync = true) // 同步加载,防止缓存击穿
public HotData getHotData(String key) {
return dataService.loadHotData(key);
}
常见问题与解决方案
问题1:缓存一致性
解决方案:
@Transactional
@CacheEvict(value = "user_cache", key = "#user.id")
public void updateUser(User user) {
userMapper.updateById(user);
// 其他业务逻辑
}
问题2:缓存序列化异常
解决方案:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson序列化
Jackson2JsonRedisSerializer<Object> serializer =
new Jackson2JsonRedisSerializer<>(Object.class);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
return template;
}
问题3:分布式锁应用
public boolean tryLock(String key, long expireTime) {
String value = UUID.randomUUID().toString();
Boolean result = redisTemplate.opsForValue()
.setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
return Boolean.TRUE.equals(result);
}
最佳实践总结
- 键设计规范:使用业务前缀+业务键的模式,如
jeecg:user:123 - 过期时间设置:根据业务特点设置合理的过期时间
- 缓存粒度控制:避免缓存大对象,尽量缓存细粒度数据
- 监控告警:建立完善的缓存监控和告警机制
- 降级策略:缓存失效时要有降级方案,保证系统可用性
结语
JeecgBoot的Redis缓存策略为企业级应用提供了稳定、高效的缓存解决方案。通过合理的配置和使用,可以显著提升系统性能,降低数据库压力。掌握这些缓存技术,将帮助开发者构建更加健壮和高效的企业应用系统。
在实际项目中,建议根据具体业务场景灵活运用各种缓存策略,并建立完善的监控体系,确保缓存系统的稳定运行。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



