缓存更新操作实例

Controller → Service(接口) → ServiceImpl(实现类,写缓存)

1.list缓存


复制代码
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {

    @Resource
    private IShopTypeService typeService;

    @GetMapping("/list")
    public Result queryTypeList() {
        // 只做一件事:调用service
        return Result.ok(typeService.queryTypeList());
    }
}
复制代码
public interface IShopTypeService extends IService<ShopType> {
    // 查询店铺类型列表(带缓存)
    List<ShopType> queryTypeList();
}

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY = "cache:shop:type:list";

    @Override
    public List<ShopType> queryTypeList() {
        // 1. 查缓存
        String json = stringRedisTemplate.opsForValue().get(KEY);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toList(json, ShopType.class);
        }

        // 2. 查数据库(标准写法!)
        List<ShopType> list = query().orderByAsc("sort").list();

        // 3. 写缓存
        stringRedisTemplate.opsForValue().set(KEY, JSONUtil.toJsonStr(list));

        return list;
    }
}

2.id缓存怎么写?

相关推荐
weixin_461408583 分钟前
Mybatis-flex小记
java·开发语言·mybatis
2601_9621771325 分钟前
【MySQL篇】聚合查询,联合查询
android·java·mysql
それども39 分钟前
IDEA接入Claude完整流程
java·ai·intellij-idea
独泪了无痕1 小时前
SpringBoot Event事件机制,轻松实现业务解耦
spring boot·后端·spring
小鹿的周先生1 小时前
Spring-AI-第2篇-ChatClient 实战:使用 DeepSeek 完成第一次 AI 对话
java·人工智能·spring
悲且狂1 小时前
SpringBoot项目改造注意事项(旧项目框架复用)
java·spring boot·后端
花间相见2 小时前
【LangChain组件03】—— LangChain Agents 执行与状态:工作流程与状态管理实战
java·前端·langchain
敲代码的嘎仔2 小时前
28届后端开发-海康威视日常实习一面(已OC)
java·开发语言·后端·面试·海康威视·实习·大厂
接着奏乐接着舞。3 小时前
【2026】73道Redis 常见面试题与参考答案
数据库·redis·后端·缓存
程序员黎剑3 小时前
Spring-Bean生命周期-构造器访问Autowired字段为null
java·后端·spring