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();
}
相关推荐
__土块__7 小时前
一次 Spring 事务传播机制源码走读:从误用 @Transactional 到理解嵌套事务的边界
spring·threadlocal·编程式事务·@transactional·事务传播·源码走读·requires_new
Java面试题总结7 小时前
Spring - Bean 生命周期
java·spring·rpc
wb043072019 小时前
使用 Java 开发 MCP 服务并发布到 Maven 中央仓库完整指南
java·开发语言·spring boot·ai·maven
二月夜10 小时前
Spring循环依赖深度解析:从三级缓存原理到跨环境“灵异”现象
java·spring
nbwenren10 小时前
Springboot中SLF4J详解
java·spring boot·后端
helx8211 小时前
SpringBoot中自定义Starter
java·spring boot·后端
EmbeddedCore12 小时前
模块化编程实践:一种面向蓝牙少量数据分包传输的轻量级缓存管理方案
缓存
rleS IONS12 小时前
SpringBoot获取bean的几种方式
java·spring boot·后端
lifewange12 小时前
Redis的测试要点和测试方法
数据库·redis·缓存
九皇叔叔13 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity