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();
}
相关推荐
自不量力的A同学38 分钟前
Spring Boot 4.0.0 正式发布
java·spring boot·后端
d***29241 小时前
【spring】Spring事件监听器ApplicationListener的使用与源码分析
java·后端·spring
v***5651 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
q***98522 小时前
什么是Spring Boot 应用开发?
java·spring boot·后端
豆奶特浓63 小时前
Java面试模拟:当搞笑程序员谢飞机遇到电商秒杀与AIGC客服场景
java·spring boot·微服务·面试·aigc·高并发·电商
f***a3464 小时前
开源模型应用落地-工具使用篇-Spring AI-高阶用法(九)
人工智能·spring·开源
踏浪无痕5 小时前
PageHelper 防坑指南:从兜底方案到根治方案
spring boot·后端
通往曙光的路上6 小时前
焚决糟糕篇
java·spring boot·tomcat
6***v4176 小时前
spring boot 项目打印sql日志和结果,使用logback或配置文件
spring boot·sql·logback
3***g2056 小时前
如何使用Spring Boot框架整合Redis:超详细案例教程
spring boot·redis·后端