JeecgBoot缓存策略:Redis分布式缓存配置与使用

JeecgBoot缓存策略:Redis分布式缓存配置与使用

【免费下载链接】JeecgBoot 🔥企业级低代码平台集成了AI应用平台,帮助企业快速实现低代码开发和构建AI应用!前后端分离架构 SpringBoot,SpringCloud、Mybatis,Ant Design4、 Vue3.0、TS+vite!强大的代码生成器让前后端代码一键生成,无需写任何代码! 引领AI低代码开发模式: AI生成->OnlineCoding-> 代码生成-> 手工MERGE,显著的提高效率,又不失灵活~ 【免费下载链接】JeecgBoot 项目地址: https://gitcode.com/jeecgboot/JeecgBoot

引言

在企业级应用开发中,缓存技术是提升系统性能的关键手段。JeecgBoot作为一款优秀的企业级低代码开发平台,深度集成了Redis分布式缓存,为开发者提供了完善的缓存解决方案。本文将深入解析JeecgBoot的Redis缓存策略,从配置到使用,帮助开发者掌握这一重要技术。

Redis缓存架构设计

整体架构概览

JeecgBoot采用Spring Boot + Spring Cache + Redis的技术栈构建缓存体系,其架构设计如下:

mermaid

核心组件说明

组件职责实现类
CacheManager缓存管理器RedisCacheManager
RedisTemplateRedis操作模板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);
}

最佳实践总结

  1. 键设计规范:使用业务前缀+业务键的模式,如jeecg:user:123
  2. 过期时间设置:根据业务特点设置合理的过期时间
  3. 缓存粒度控制:避免缓存大对象,尽量缓存细粒度数据
  4. 监控告警:建立完善的缓存监控和告警机制
  5. 降级策略:缓存失效时要有降级方案,保证系统可用性

结语

JeecgBoot的Redis缓存策略为企业级应用提供了稳定、高效的缓存解决方案。通过合理的配置和使用,可以显著提升系统性能,降低数据库压力。掌握这些缓存技术,将帮助开发者构建更加健壮和高效的企业应用系统。

在实际项目中,建议根据具体业务场景灵活运用各种缓存策略,并建立完善的监控体系,确保缓存系统的稳定运行。

【免费下载链接】JeecgBoot 🔥企业级低代码平台集成了AI应用平台,帮助企业快速实现低代码开发和构建AI应用!前后端分离架构 SpringBoot,SpringCloud、Mybatis,Ant Design4、 Vue3.0、TS+vite!强大的代码生成器让前后端代码一键生成,无需写任何代码! 引领AI低代码开发模式: AI生成->OnlineCoding-> 代码生成-> 手工MERGE,显著的提高效率,又不失灵活~ 【免费下载链接】JeecgBoot 项目地址: https://gitcode.com/jeecgboot/JeecgBoot

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值