SpringCache
SpringCache介绍
Spring Cache是-一个框架, 实现了基于注解的缓存功能,只需要简单地加一-个注解,就能实现缓存功能。 Spring Cache提供了一层抽象, 底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。 CacheManager是Spring提供的各种缓存技术抽象接口。 针对不同的缓存技术需要实现不同的CacheManager:
EhCacheCacheManager 使用EhCache作为缓存技术 GuavaCacheManager 使用Google的GuavaCache作为缓存技术 RedisCacheManager 使用Redis作为缓存技术
Spring Cache常用注解
@EnableCaching:开启缓存注解功能 @Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回数据; 若没有数据,调用方法并将方法返回值放到缓存中 @CachePut:将方法的返回值放到缓存中 @CacheEvict:将一条或多条数据从缓存中删除
在springboot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。
例如:使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。
@CachePut使用方法:
在方法上加入@CachePut注解,
@CachePut(value="userCache",key="")
value:缓存的名称,每个缓存名称下面可以有多个key
key:缓存的key。可以设置为#result.属性(result为方法的返回值)
或者#参数名.属性 等等
@CacheEvict使用方法:
@CacheEvict(value="userCache",key="")
key可以是:#p0.id;#user.id;#root.args[0].id;#result.id(建议使用)
@Cacheable使用方法
@Cacheable(value="userCache",key="#id")
注意:该方法解决缓存穿透的一种方式,缓存空对象:预防高并发访问不存在的数据,服务端直接把控制存到缓存中去,客户端再次访问,直接返回空值
那么这种方式如何作字符串拼接呢
@Cacheable(value="userCache",key="#参数.id+'_'+#参数.name")
在项目中使用Spring Cache的使用步骤(使用redis缓存技术)
1、导入maven坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2、配置application.yml
spring: cache: redis: time-to-live: 1800000
3、在启动类上加入@EnableCaching注解,开启缓存注解功能
4、在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作。