Hysteretic query caching as an example

I am trying to figure out how the caching of Hystrix requests works, but I do not follow the wiki or the walk-through examples that they provide in their docs.

Essentially, I have the following subclass of 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); } } 

So, I feel like I'm going against the grain here. I believe that Hystrix offers built-in caching, as evidenced by ' cacheKey ' , but I cannot find any working examples. I do not want to reinvent the wheel here and build caching in my teams if something is already provided out of the box.

So I ask: what does the caching request with Hystrix look like (exactly)? How are entries added to the cache? How / when does cache redden? Is it customizable (expiration date, maximum size, etc.)?

+7
java caching fault-tolerance hystrix
source share
1 answer

In the documentation related to here ,

Request caching is activated by implementing the getCacheKey() method for the HystrixCommand ...

You have not implemented getCacheKey() ,

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

Then you will also need a HystrixRequestContext

 HystrixRequestContext context = HystrixRequestContext.initializeContext(); 

What (again, in the documentation)

Typically, this context will be initialized and terminated with a ServletFilter that wraps the user request or some other lifecycle binding.

Then I believe that you cannot change the signature of the execute() method ( doExecute() not part of the interface) instead, you pass the parameter to your command constructor and please annotate execute with @Override to get a compiler error if you forgot and then

 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. 
+6
source share

All Articles