所谓缓存,就是将程序或系统经常要调用的对象存放在一个可以快速访问的地方,一便其使用时可以快速取到,不必再调用具体业务。这样做可以减少系统开销,提高系统效率。二级缓存则是由于在分布式系统中,一般会使用集中缓存来缓存数据,例如redis,此时集中式缓存在高并发场景下时,就很容易被击垮。l2cache则是以redis作为二级缓存,内存作为一级缓存,让并发时的大部分请求从内存中响应,这样最大程度提高缓存效能。同时通过一定的设计,l2cache支持自动缓存降级,可以防缓存击穿,同时可以很容易的拓展为其它多级缓存。让缓存使用更容易。
l2cache执行流程图
快速入门
1.在maven管理的spring-boot项目中引入依赖,(建议使用spring-boot版本1.4以上,1.4以下未测试过)
<dependency>
<groupId>com.gitee.reger</groupId>
<artifactId>spring-boot-starter-l2cache</artifactId>
<version>${spring-boot-starter-l2cache.version}</version>
</dependency>
2.在spring-boot项目的配置文件’application.yml’中增加redis的配置项
spring:
redis:
host: localhost
port: 6379
# password:
3.通过@L2Cache
开始体验二级缓存
在需要使用二级缓存加载数据的方法上,加上注解@L2Cache(key=’用来生成cachekey的spel表达式’,timeOut=’缓存超时时间’)
例如
@L2Cache(key="'test.id.'+#id",timeOut=2000)
public Object findById(int id) {
System.err.println("进入缓存执行的方法");
return "hello word ! findById " +id;
}
4.通过@L2PutCache强制更新二级缓存中的数据
有时在某些操作完毕后,需要主动更新缓存,使缓存立即失效,此时便需要强制更新二级缓存的数据。在这个时候,你只需要在方法上添加@L2PutCache(key=’用来生成cachekey的spel表达式’,timeOut=’缓存超时时间’)。
例如
@L2PutCache(key="'test.id.'+#id",timeOut=20000)
public Object updateById(int id) {
System.err.println("执行完毕会强制缓存...");
return "hello word ! updateById " +id;
}
5.通过@L2DelCache删除二级缓存中的数据
在一些操作完毕后,数据被删除,需要在缓存中立即生效。在这个时候,你只需要在方法上添加@L2DelCache(key=’用来生成cachekey的spel表达式’)。
例如
@L2DelCache(key="'test.id.'+#id")
public void del(int id) {
System.err.println("执行完毕会清理缓存...");
}
相关资源
spring-boot-starter-l2cache git地址