hystrix支持將一個請求結果緩存起來,下一個具有相同key的請求將直接從緩存中取出結果,減少請求開銷。要使用hystrix cache功能
第一個要求是重寫getCacheKey(),用來構造cache key;
第二個要求是構建context,如果請求B要用到請求A的結果緩存,A和B必須同處一個context。
通過HystrixRequestContext.initializeContext()和context.shutdown()可以構建一個context,這兩條語句間的所有請求都處於同一個context。
測試代碼如下:
HystrixCommandCache.java
public class HystrixCommandCache extends HystrixCommand<Boolean>{
private final int value;
private final String value1;
protected HystrixCommandCache(int value, String value1) {
super(HystrixCommandGroupKey.Factory.asKey("RequestCacheCommandGroup"));
this.value = value;
this.value1 = value1;
}
// 返回結果是cache的value
@Override
protected Boolean run() {
return value == 0 || value % 2 == 0;
}
// 構建cache的key
@Override
protected String getCacheKey() {
return String.valueOf(value) + value1;
}
}
HystrixCommandCacheTest.java
public class HystrixCommandCacheTest {
@Test
public void testWithoutCacheHits() {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
assertTrue(new HystrixCommandCache(2,"HLX").execute());
assertFalse(new HystrixCommandCache(1,"HLX").execute());
assertTrue(new HystrixCommandCache(0,"HLX").execute());
assertTrue(new HystrixCommandCache(58672,"HLX").execute());
} finally {
context.shutdown();
}
}
@Test
public void testWithCacheHits() {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
HystrixCommandCache command2a = new HystrixCommandCache(2,"HLX");
HystrixCommandCache command2b = new HystrixCommandCache(2,"HLX");
HystrixCommandCache command2c = new HystrixCommandCache(2,"HLX1");
assertTrue(command2a.execute());
// 第一次執行,不應該是從緩存中獲取
assertFalse(command2a.isResponseFromCache());
assertTrue(command2b.execute());
// 第二次執行,通過isResponseFromCache()方法判斷是否是從緩存中獲取的
assertTrue(command2b.isResponseFromCache());
//雖然是第三次執行,但是getCacheKey()的緩存key值不一樣,依然無法從緩存中獲取
assertTrue(command2c.execute());
assertFalse(command2c.isResponseFromCache());
} finally {
context.shutdown();
}
// 開啟一個新的context
context = HystrixRequestContext.initializeContext();
try {
HystrixCommandCache command3a = new HystrixCommandCache(2,"HLX");
HystrixCommandCache command3b = new HystrixCommandCache(2,"HLX");
assertTrue(command3a.execute());
// 第一次請求,不應該從緩存中獲取
assertFalse(command3a.isResponseFromCache());
//沒有執行excute(),isResponseFromCache()永遠返回是true
assertFalse(command3b.isResponseFromCache());
} finally {
context.shutdown();
}
}
}
以測試demo的testWithCacheHits()為例,command2a、command2b、command2c同處一個context,前兩者的cache key都是2HLX(見getCacheKey()),所以command2a執行完后把結果緩存,command2b執行時就不走run()而是直接從緩存中取結果了,而command2c的cache key是2HLX1,無法從緩存中取結果。
注:isResponseFromCache()方法用於檢測是否是從緩存中獲取;
參考文獻:http://www.jianshu.com/p/b9af028efebb
