You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot缓存问题:@Cacheable与@CachePut统一键配置咨询

Spring Cache 统一缓存键配置方案

针对你的场景,我们可以利用两个方法共有的client参数作为核心缓存键,配合Spring Cache的注解属性实现缓存的统一管理。以下是修改后的完整代码示例:

查询方法(@Cacheable)

import org.springframework.data.domain.Sort;
import java.util.stream.Collectors;

@Cacheable(value = "systems", key = "#client")
public List<SystemDTO> getAllSystem(String client, Integer pageNumber, Integer pageSize, String sortBy, String sortDirection) {
    // 补全Sort对象的初始化逻辑(原代码缺失该变量)
    Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortBy);
    Pageable p = PageRequest.of(pageNumber, pageSize, sort);
    
    Page<SystemEntity> sysPage = sysDao.findAll(p);
    List<SystemEntity> sysEntities = sysPage.getContent();
    
    // 补充SystemEntity到SystemDTO的转换逻辑(根据你的实际DTO结构调整)
    return sysEntities.stream()
            .map(this::convertSystemEntityToDTO)
            .collect(Collectors.toList());
}

// 新增转换方法示例
private SystemDTO convertSystemEntityToDTO(SystemEntity entity) {
    SystemDTO dto = new SystemDTO();
    dto.setSystemId(entity.getSystemId());
    dto.setCreatedDate(entity.getCreatedDate());
    // 其他字段映射
    return dto;
}

新增方法(@CachePut)

@CachePut(value = "systems", key = "#client")
public List<SystemDTO> addSystem(String client, SystemEntity sys) {
    Integer maxId = sysDao.findSystemMaxId();
    sys.setSystemId(maxId);
    sys.setCreatedDate(new Date());
    sysDao.save(sys);
    
    // 新增后返回最新的系统列表,触发缓存更新
    // 这里可根据业务需求指定分页参数,示例返回全量列表
    return getAllSystem(client, 0, Integer.MAX_VALUE, "systemId", "asc");
}

关键说明

  • 统一缓存键:两个注解都使用value = "systems"指定缓存名称,key = "#client"绑定公共的client参数,确保同一客户端的缓存条目被统一维护。
  • 类型一致性:调整addSystem的返回类型为List<SystemDTO>,与getAllSystem的返回类型保持一致,保证缓存更新时的数据格式匹配。
  • 缓存自动更新:@CachePut会在方法执行完成后,用返回的最新列表覆盖对应client的缓存条目,避免查询到旧数据。

内容的提问来源于stack exchange,提问作者Sahas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:45:13