com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult-我对Hystrix-Javanica给出的这个@CacheResult注释有点困惑。根据文档-它可以缓存HystrixCommand的结果。在下面的示例中,服务总是执行带@HystrixCommand注释的方法,并且不理解为什么@CacheResult没有起作用。
Map<String, String> map = new HashMap<>();
@CacheResult(cacheKeyMethod="getCacheKey")
@HystrixCommand(fallbackMethod = "callStudentServiceAndGetData_Fallback", commandProperties= {
@HystrixProperty(name="requestCache.enabled" , value="true")
} )
public String callStudentServiceAndGetData(@CacheKey String schoolname) {
System.out.println("Getting School details for " + schoolname);
String response = restTemplate.exchange("http://localhost:8098/getStudentDetailsForSchool/{schoolname}",HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}, schoolname).getBody();
map.put(schoolname, response);
return response;
}
public String getCacheKey (String key) {
return map.get(key);
}
private String callStudentServiceAndGetData_Fallback(String schoolname) {
return "Service down. "+ new Date();
}我没有找到任何使用Javanica注释的Hystrix的有用示例。你能看看我这里漏掉了什么吗?提亚
发布于 2018-04-08 11:16:33
对我来说,你似乎遗漏了以下内容:
1) Hystrix使用内部缓存实现,这意味着您不需要使用某种存储(在您的示例中为map ),也不需要手动执行put/get。您应该做的唯一一件事就是指定缓存键。
2)要指定将成为Hystrix键的内容,可以使用@CacheKey注释或cacheKeyMethod="getCacheKey"注释参数。没有理由同时使用这两种方法。有关更多选项,请查看javanica docs
3) Hystrix缓存仅在同一HTTP请求执行期间存在。这意味着如果您将通过HTTP连续调用您的服务两次,具有相同缓存键的值将会缺失。所以Hystrix缓存可能不是你要找的东西。
4)要激活缓存功能,您必须调用
HystrixRequestContext c = HystrixRequestContext.initializeContext();在命令执行之前和
c.shutdown();之后。
Web filter是添加此类初始化的合适位置。有关mo的详细信息,请访问Hystrix caching
https://stackoverflow.com/questions/49698975
复制相似问题