原文地址:https://www.jianshu.com/p/03b289439de2
springboot中使用說明
jetcache原理參見:https://www.jianshu.com/p/8cff0062a899
jetcache 源碼參見:https://github.com/alibaba/jetcache.git
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); } }
其中需要注意的是:
- 在@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_CN
4 在對應接口或者類方法上增加緩存注解
具體注解詳細說明請參考:https://github.com/alibaba/jetcache/wiki/MethodCache_CN
4.1增加緩存
接口Service對應的代碼如下:
public interface Service { @Cached(cacheType = CacheType.LOCAL) int printSay(String message); }
只需要在對應接口的方法上增加注解@Cache,即可以在對應這個方法增加緩存。
4.2緩存刷新
對應的代碼如下:
public interface Service { @Cached(cacheType = CacheType.LOCAL) @CacheRefresh(refresh = 60) int printSay(String message); }
@CacheRefresh上面的配置是1分鍾刷新一次
4.3 緩存失效
對應的代碼如下:
@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對應的緩存功能也被開啟了。
作者:瑜騏
鏈接:https://www.jianshu.com/p/03b289439de2
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。