Spring Cache 使用

Spring Cache 使用

是 Spring 提供的的缓存解决方案,它并非是一个具体的缓存实现。

Spring Cache 的特点:
声明式缓存:通过在方法上添加注解,如 @Cacheable、@CachePut、@CacheEvict 等来声明缓存的行为,无需手动编写缓存代码。
多种缓存支持:Spring Cache 提供了对多种缓存框架的支持,包括 Redis、Ehcache、Guava Cache、Caffeine 等,可以根据需要选择合适的缓存实现。
缓存策略配置:可以通过配置文件或者编程方式来配置缓存的策略,包括缓存的过期时间、缓存的淘汰策略等。
注解灵活应用:通过在方法上添加不同的注解,可以实现缓存的读取、更新和清除等操作,根据业务需求进行灵活配置。
缓存切面自动代理:Spring Cache 通过 AOP 技术,利用代理模式在方法执行前后拦截,自动处理缓存相关的操作,对业务代码无侵入

Spring Cache+redis+maven
0.导入Spring Cache和redis相关的maven依赖;
1.启动类添加@EnableCaching注解,开启缓存注解功能;
2.在用户端接口的list方法上添加@Cacheable注解,获取数据并添加到缓存
3.在管理接口save,delete,update等方法上加入CacheEvick注解,删除缓存

1.引入相关依赖

org.springframework.boot
spring-boot-starter-parent
2.7.18




org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-cache

2.启用缓存
在启动类上添加 @EnableCaching 注解

3.引入并配置具体的缓存实现application.yml
redis:
host: ${sky.redis.host}
port: ${sky.redis.port}
password: ${sky.redis.password}
database: ${sky.redis.database}

4.redis cache的使用:
@Cacheable(cacheNames = "RedisCache", key = "#id")
public String queryById(int id) {
log.info("queryById,id={}", id);
return "value" + id;
}

@CacheEvict(cacheNames = "myCache", key = "#id")
public void deleteById(int id) {
log.info("deleteById,id={}", id);
}

@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result delete(@RequestParam List ids) {
setmealService.deleteBatch(ids);
return Result.success();
}

5.Spring Cache 注解 汇总:
@Cacheable 标记在方法上,表示方法的返回值会被缓存。当方法被调用时,会先检查缓存中是否存在对应的结果,如果存在,则直接返回缓存中的值,如果不存在,则执行方法体,并将返回值缓存起来。
@CachePut 标记在方法上,表示方法的返回值会被缓存。不同于 @Cacheable,@CachePut 每次都会执行方法体,并将返回值缓存起来;它通常用于更新缓存。
@CacheEvict 标记在方法上,表示清除缓存项。通过设置不同的属性来清除的相应缓存项,通过 key 属性来清除特定键的缓存项,通过 allEntries 属性来清除所有缓存项。
@Caching 用于多个缓存操作的组合,可以同时使用 @Cacheable、@CachePut 和 @CacheEvict 等注解。
@CacheConfig标记在类上,用于指定该类中所有方法的缓存相关配置,包括缓存名称、缓存管理器等。

java tool:

Spring Cache+redis+maven
Spring Task定时任务介绍
HttpClient (apache 子项目 http请求帮助工具包)
webscoct
Apache POL

posted @ 2025-07-14 15:51  大树2  阅读(15)  评论(0)    收藏  举报