缓存更新操作实例

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缓存怎么写?

相关推荐
用户398346161204 小时前
Go-Spring 实战第 18 课 —— App 使用:启动、配置与运行期扩展
spring·go
zzz_23684 小时前
【Spring】面试突击系列(一):IoC 与 DI 深度解析
java·spring·面试
于先生吖4 小时前
前后端分离体育服务项目,场馆计费+线下赛事排行小程序部署开发教程
java·小程序·uni-app
RemainderTime5 小时前
Spring Boot脚手架集成 Spring Security实现生产级RBAC鉴权
spring boot·后端·spring
闪电悠米5 小时前
黑马点评-秒杀优化-01_async_seckill_idea
java·数据库·ide·redis·分布式·缓存·intellij-idea
摇滚侠5 小时前
IDEA 创建 Java 项目 lib 和 resources
java·ide·intellij-idea
宸津-代码粉碎机5 小时前
Spring AI企业级Agent实战|多工具自动规划+并行调度落地,彻底解决复杂业务AI任务编排问题
java·大数据·人工智能·spring boot·python·spring
lixia0417mul25 小时前
flink接入spring体系
java·spring·flink
biubiubiu07065 小时前
自定义starter 可以导入SpringBoot直接使用
java·spring boot·spring
TFHoney5 小时前
当 AI 真正走进你的终端:Claude Code 使用指南
java·人工智能·ai编程