原文地址: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對應的緩存功能也被開啓了。