springboot中使用說明
jetcache原理參見:http://www.reibang.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注解對應(yīng)的scanBasePackages中增加jetcache自動配置對應(yīng)的包。
- 增加注解EnableMethodCache,并制定開啟緩存對應(yīng)的包路徑匾灶。
- 增加注解EnableCreateCacheAnnotation金句,這個注解是開啟對應(yīng)的CreateCache注解。
3 在application.yml中增加對應(yīng)的緩存全局配置
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 在對應(yīng)接口或者類方法上增加緩存注解
具體注解詳細說明請參考:https://github.com/alibaba/jetcache/wiki/MethodCache_CN
4.1增加緩存
接口Service對應(yīng)的代碼如下:
public interface Service {
@Cached(cacheType = CacheType.LOCAL)
int printSay(String message);
}
只需要在對應(yīng)接口的方法上增加注解@Cache,即可以在對應(yīng)這個方法增加緩存。
4.2緩存刷新
對應(yīng)的代碼如下:
public interface Service {
@Cached(cacheType = CacheType.LOCAL)
@CacheRefresh(refresh = 60)
int printSay(String message);
}
@CacheRefresh上面的配置是1分鐘刷新一次
4.3 緩存失效
對應(yīng)的代碼如下:
@CacheInvalidate(name = "c1", key = "args[0]")
void delete(String id);
表示從緩存名稱為c1,將對應(yīng)key為id值的記錄從緩存c1中刪除叁温。
4.4 緩存更新
對應(yīng)的代碼如下:
@CacheUpdate(name = "c1", key = "#id", value = "args[1]")
void update(String id, int value);
刷新緩存對應(yīng)的緩存名稱為c1,緩存中對應(yīng)的key為id的值核畴,更新key的值為value的值膝但。
4.5 緩存開啟
對應(yīng)的代碼如下:
@Cached(enabled = false)
public int countWithDisabledCache(){
return count++;
}
@EnableCache
public int enableCacheWithAnnoOnClass(){
return countWithDisabledCache();
}
從上面代碼中可以看出方法countWithDisabledCache對應(yīng)的方法定義了緩存功能,但是這個功能被關(guān)閉了谤草,而方法enableCacheWithAnnoOnClass方法上開啟了緩存的功能跟束,則方法countWithDisabledCache雖然本身的緩存被關(guān)閉了莺奸,但是調(diào)用方法開啟了,則方法countWithDisabledCache對應(yīng)的緩存功能也被開啟了冀宴。