2014-11-25 221 views
7

我想弄清楚如何Hystrix request caching的工作原理,但我没有遵循维基或他们在他们的文档中提供的端到端的例子。Hystrix请求缓存示例

从本质上讲,我有以下HystrixCommand子类:

public class GetFizzCommand extends HystrixCommand<Fizz> { 
    private Long id; 
    private Map<Long,Fizz> fizzCache = new HashMap<Long,Fizz>(); 

    void doExecute(Long id) { 
     this.id = id; 
     execute(); 
    } 

    @Override 
    public Fizz run() { 
     return getFizzSomehow(); 
    } 

    @Override 
    public Fizz getFallback() { 
     // Consult a cache somehow. 
     // Perhaps something like a Map<Long,Fizz> where the 'id' is the key (?) 
     // If the 'id' exists in the cache, return it. Otherwise, give up and return 
     // NULL. 
     fizzCache.get(id); 
    } 
} 

所以我觉得我要对粮食这里。我相信 Hystrix提供内置缓存,如'cacheKey'所示,但我找不到任何工作示例。如果已经提供了开箱即用的功能,我不想在这里重新发明轮子并将缓存构建到我的命令中。

所以我问:什么请求缓存看起来像Hystrix(完全)?如何将条目添加到缓存中?如何/何时缓存刷新?它是否可配置(过期,最大尺寸等)?

+1

你可以读取HystrixCommand的实现。起点将是方法[HystrixCommand.isResponseFromCache())](http://grepcode.com/file/repo1.maven.org/maven2/com.netflix.hystrix/hystrix-core/1.3.3/com/ netflix/hystrix/HystrixCommand.java#HystrixCommand.isResponseFromCache())(链接到* grepcode.com *)。 – MicSim 2014-11-28 16:43:58

回答

6

每您链接到here文档,

请求缓存由一个HystrixCommand对象上执行getCacheKey()方法启用...

您还没有实现getCacheKey()

@Override 
protected String getCacheKey() { 
    return String.valueOf(id); // <-- changed from `value` in example 
} 

那你还需要一个HystrixRequestContext

HystrixRequestContext context = HystrixRequestContext.initializeContext(); 

,它是(再次,每文档)

典型地,这上下文将经由ServletFilter,它包装的用户请求或一些其他生命周期钩被初始化和关闭。

那么我相信你无法与@Override改变execute()这样的方法签名(doExecute()不是接口的一部分),而不是你传递参数给你的命令构造函数和请注释execute所以你得到一个编译器错误,如果你忘了然后

HystrixRequestContext context = HystrixRequestContext.initializeContext(); 
GetFizzCommand commandA = new GetFizzCommand(2L); 
GetFizzCommand commandB = new GetFizzCommand(2L); 
Fizz a = commandA.execute(); // <-- should not be cached 
Fizz b = commandB.execute(); // <-- should be cached.