spring 缓存

1.spring缓存注解,可以丢在controller,也可以丢在service,也可以丢在mapper。

2.手动操作缓存使用:

java 复制代码
    @Autowired
    private CacheManager cacheManager;

3.添加缓存

java 复制代码
//添加缓存
@Override
@Cacheable(cacheNames = "test", key = "'test_model' + #id",unless="#result == null") //如果结果为空,不缓存
public TestModel selectByIdCache(Long id) {
    return baseMapper.selectById(id);
}
//等于代码:
@Override
public TestModel selectByIdCache(Long id) {
    TestModel model baseMapper.selectById(id);
    if(model!=null){//如果结果为空,不缓存
    	Cache cache = cacheManager.getCache("test");
    	cache.put("test_model"+id,model);
    }
    return model;
}

4.删除缓存

java 复制代码
//注解删除缓存
@CacheEvict(cacheNames = "test", key = "'test_model' + #bo.id")
@Override
public Boolean updateByBo(TestModelBo bo) {
}
//等于代码:
@Override
public Boolean updateByBo(TestModelBo bo) {
	Cache cache = cacheManager.getCache("test");
    cache.evict("test_model"+bo.getId());
}

5.清空缓存

java 复制代码
//注解清空缓存
@CacheEvict(cacheNames = "test", allEntries = true)
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
}
//等于代码:
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
	Cache cache = cacheManager.getCache("test");
    cache.clear();
}
相关推荐
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
困知勉行19853 小时前
springboot整合redis
java·spring boot·redis
中年程序员一枚3 小时前
Springboot报错Template not found For name “java/lang/Object_toString.sql
java·spring boot·python
fanruitian4 小时前
Springboot项目父子工程
java·数据库·spring boot
柒.梧.4 小时前
Spring核心知识全解析:从入门实战到进阶
java·后端·spring
全栈独立开发者5 小时前
点餐系统装上了“DeepSeek大脑”:基于 Spring AI + PgVector 的 RAG 落地指南
java·人工智能·spring
super_lzb5 小时前
mybatis拦截器ParameterHandler详解
java·数据库·spring boot·spring·mybatis
longson.5 小时前
怎样避免空间碎片而且高效的分配空间
嵌入式硬件·缓存
我是Superman丶5 小时前
【异常】Spring Ai Alibaba 流式输出卡住无响应的问题
java·后端·spring