2

I am trying to create a cache key with multiple parameter values.

@Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id")
private JSONObject getData(String name, String id) throws Exception {

From the above scenario, I name is a mandatory field while id is optional. I want to create key in such a way that,

  1. If name = "test" and id = null, cache key must be cache_name_test
  2. If name = "test" and id = "2", cache key must be cache_name_test_2

Currently, the key is forming something like "cache_name_test_null" if the id is not passed in the parameter value

Is it possible to create such key with @Cacheable annotation?

James Z
  • 12,209
  • 10
  • 24
  • 44
r123
  • 578
  • 8
  • 26

1 Answers1

3

Solution

It's doable, but you need to wrap 2 @Cachable annotations in a @Caching annotation.

@Caching(
      cacheable = {
            @Cacheable(cacheNames = "cache_name_", key = "#name + '_' + #id", condition = "#id != null"),
            @Cacheable(cacheNames = "cache_name_", key = "#name", condition = "#id == null")
      }
    )
public JSONObject getData(String name, String id) throws Exception {

Note on private methods

You are using the @Caching annotation on a private method. This doesn't work. Those annotations only work on public methods being called from outside the class. See this Stack Overflow answer: https://stackoverflow.com/a/16899739/2082699

Tom Cools
  • 1,098
  • 8
  • 23
  • This works with public methods, but the condition #id != null is not working – r123 Apr 18 '20 at 11:22
  • According to the official SPEL manual, this should work tho. Could you maybe add your current code? Maybe the problem is somewhere else? – Tom Cools Apr 18 '20 at 13:00
  • I made a mistake by giving incorrect key name in the condition – r123 Apr 20 '20 at 05:49