@Caching with multiple keys

I have a service that accepts a DTO and returns some result:

@Override public int foo(Bar bar) { .... } 

The bar is as follows (simplified):

 public class Bar { public int id; public String name; public String baz; @Override public int hashCode() { //this is already being defined for something else ... } @Override public boolean equals(Object o) { //this is already being defined for something else ... } } 

I want to use @Cacheable in the foo method; however, I want a hash on the id and name properties, but not baz. Is there any way to do this?

+2
source share
3 answers

Yes, you can specify using the Spring -EL expression along these lines:

 @Override @Cacheable(key="#bar.name.concat('-').concat(#bar.id)") public int foo(Bar bar) { .... } 

or define the changed hashCode character in the panel and call this:

 @Override @Cacheable(key="#bar.hashCodeWithIdName") public int foo(Bar bar) { .... } 
+7
source

You can also use this approach.

 @Override @Cacheable(key="{#bar.name, #bar.id}") public int foo(Bar bar) { .... } 

It is suggested not to use the hash code as @Cacheable keys for multiple method arguments

+9
source

Both answers from @Biju and @vsingh are correct; but I would like to add another alternative, if the Bar object you are trying to cache is complex or the foo method contains a large number of parameters using SpEL, it may not be the ideal solution for generating a key.

Alternatively, you can consider keyGenerator .

Example:

 @Override @Cacheable(value="barCahceKey", keyGenerator="barKeyGenerator") public int foo(Bar bar) { .... } @Component public class BarKeyGenerator implements KeyGenerator { @Override public Object generate(Object o, Method method, Object... objects) { // TODO logic to generate unique key return "Bar_Key_Generator_With_Params_etc"; } } 

With this approach, you have complete flexibility in building the key.

KeyGenerator API

+1
source

Source: https://habr.com/ru/post/1316696/


All Articles