原文地址:https://www.jianshu.com/p/03b289439de2java
springboot中使用说明
jetcache原理参见:https://www.jianshu.com/p/8cff0062a899
jetcache 源码参见:https://github.com/alibaba/jetcache.gitgit
1 引入pom依赖
<dependency> <groupId>com.alicp.jetcache</groupId> <artifactId>jetcache-starter-redis</artifactId> <version>2.4.4</version> </dependency>
2 在启动类上增长注解
@SpringBootApplication(scanBasePackages = {"com.example.firstjetcacheprj.business","com.alicp.jetcache.autoconfigure"}) @EnableMethodCache(basePackages = "com.example.firstjetcacheprj.business") @EnableCreateCacheAnnotation public class FirstjetcacheprjApplication { public static void main(String[] args) { SpringApplication.run(FirstjetcacheprjApplication.class, args); } }
其中须要注意的是:github
- 在@SpringBootApplication注解对应的scanBasePackages中增长jetcache自动配置对应的包。
- 增长注解EnableMethodCache,并制定开启缓存对应的包路径。
- 增长注解EnableCreateCacheAnnotation,这个注解是开启对应的CreateCache注解。
3 在application.yml中增长对应的缓存全局配置
jetcache: statIntervalMinutes: 15 areaInCacheName: false local: default: type: linkedhashmap keyConvertor: fastjson otherCacheName: type: xxx keyConverter: yyy remote: default: type: redis keyConvertor: fastjson valueEncoder: java valueDecoder: java poolConfig: minIdle: 5 maxIdle: 20 maxTotal: 50 host: 127.0.0.1 port: 6379
配置中字段讲解能够参考https://github.com/alibaba/jetcache/wiki/Config_CNredis
4 在对应接口或者类方法上增长缓存注解
具体注解详细说明请参考:https://github.com/alibaba/jetcache/wiki/MethodCache_CNspring
4.1增长缓存
接口Service对应的代码以下:json
public interface Service { @Cached(cacheType = CacheType.LOCAL) int printSay(String message); }
只须要在对应接口的方法上增长注解@Cache,便可以在对应这个方法增长缓存。缓存
4.2缓存刷新
对应的代码以下:springboot
public interface Service { @Cached(cacheType = CacheType.LOCAL) @CacheRefresh(refresh = 60) int printSay(String message); }
@CacheRefresh上面的配置是1分钟刷新一次app
4.3 缓存失效
对应的代码以下:spa
@CacheInvalidate(name = "c1", key = "args[0]") void delete(String id);
表示从缓存名称为c1,将对应key为id值的记录从缓存c1中删除。
4.4 缓存更新
对应的代码以下:
@CacheUpdate(name = "c1", key = "#id", value = "args[1]") void update(String id, int value);
刷新缓存对应的缓存名称为c1,缓存中对应的key为id的值,更新key的值为value的值。
4.5 缓存开启
对应的代码以下:
@Cached(enabled = false) public int countWithDisabledCache(){ return count++; } @EnableCache public int enableCacheWithAnnoOnClass(){ return countWithDisabledCache(); }
从上面代码中能够看出方法countWithDisabledCache对应的方法定义了缓存功能,可是这个功能被关闭了,而方法enableCacheWithAnnoOnClass方法上开启了缓存的功能,则方法countWithDisabledCache虽然自己的缓存被关闭了,可是调用方法开启了,则方法countWithDisabledCache对应的缓存功能也被开启了。