0
votes

com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult- I am bit confused about this @CacheResult annotation given by Hystrix-Javanica. Per documentation- it can cache the result for a HystrixCommand. In the following example, service is always executing the @HystrixCommand annotated method and don't understand why the @CacheResult didn't come into play.

    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();
    }

I didn't find any useful example of Hystrix with Javanica annotation. Can you please have a look what I am missing here? TIA

1

1 Answers

0
votes

For me it looks like you are missing following:

1) Hystrix uses internal cache implementation which means that you do not need to use some kind of storage( map in your example ) and put/get manually. The only one thing that you should do is to specify what will be the cache key.

2) To specify what will be the Hystrix key you can use @CacheKey annotation, or cacheKeyMethod="getCacheKey" annotation parameter. No reasons to use both of them. For more options please check javanica docs

3) Hystrix cache lives only during same HTTP request execution. It means that if you will call your service via HTTP twice in a row with the same cache key value will be absent. So Hystrix cache might be not the thing you are looking for.

4) To activate cache feature you have to call

HystrixRequestContext c = HystrixRequestContext.initializeContext();

Before command execution and

 c.shutdown();

after.

Web filter is the right place to add such kind of initialization. For mo details please follow Hystrix caching