springboot使用自带缓存cache
1、pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
2、main启动类加入@EnableCaching
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
3、自定义缓存key的命名规则
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
// 自定义缓存的 key生成
@Component
public class MyKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(o.getClass().getSimpleName())
.append("_")
.append(method.getName())
.append("_")
.append(StringUtils.arrayToDelimitedString(objects, "_"));
return stringBuffer.toString();
}
}
4、在类上使用,访问类所有的方法都缓存
import com.pingan.domain.Student;
import com.pingan.mapper.StudentMapper;
import com.pingan.service.StudentService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 在类上加 @Cacheable 代表类下面所有的方法都缓存,cacheNames随便起,keyGenerator为自定义缓存key的bean
@Service("studentService")
@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public Student queryById(Integer id) {
return this.studentMapper.queryById(id);
}
}
在方法上使用,访问此方法才会缓存
@Cacheable(cacheNames = "StudentServiceCache",keyGenerator = "myKeyGenerator")
public Student queryById(Integer id) {
return this.studentMapper.queryById(id);
}
5、在更新和插入的方法上加上 @CacheEvict 清空缓存
@CacheEvict(cacheNames = "StudentServiceCache",allEntries = true)
public Student insert(Student student) {
this.studentMapper.insert(student);
return student;
}
6、定时任务清缓存
通过定时任务去清缓存
@Autowired
private Demo01Controller demo01Controller;
@Scheduled(cron = "0/4 * * * * *")
public void test03() {
demo01Controller.test02(); // test02方法上有注解 @CacheEvict
}
ps: 本质利用了java类的内容,对tomcat会造成一定的压力
分类:
代码Demo
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义