【问题标题】:Hystrix Javanica @CacheResultHystrix Javanica @CacheResult
【发布时间】:2018-09-16 20:19:40
【问题描述】:

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 示例。你能看看我在这里缺少什么吗? TIA

【问题讨论】:

    标签: spring-boot spring-cloud-netflix hystrix netflix


    【解决方案1】:

    对我来说,您似乎缺少以下内容:

    1) Hystrix 使用内部缓存实现,这意味着您不需要使用某种存储(示例中的映射)和手动放置/获取。您应该做的唯一一件事是指定缓存键。

    2) 要指定 Hystrix 密钥,您可以使用 @CacheKey 注释或 cacheKeyMethod="getCacheKey" 注释参数。没有理由同时使用它们。更多选项请查看javanica docs

    3) Hystrix 缓存仅存在于相同的 HTTP 请求执行期间。这意味着如果您将通过 HTTP 连续两次调用您的服务,并且具有相同的缓存键值将不存在。所以 Hystrix 缓存可能不是你要找的东西。

    4) 要激活缓存功能,您必须调用

    HystrixRequestContext c = HystrixRequestContext.initializeContext();
    

    在命令执行之前和

     c.shutdown();
    

    之后。

    Web 过滤器是添加此类初始化的正确位置。详情请关注Hystrix caching

    【讨论】:

      猜你喜欢
      • 2019-06-03
      • 2014-12-19
      • 2016-10-26
      • 2015-06-13
      • 2016-11-01
      • 2014-12-09
      • 2016-11-20
      • 1970-01-01
      • 2017-01-15
      相关资源
      最近更新 更多