0

I am trying to store the result returned from a method into Cache ( using Caffeine cache). So in the below method, I want the value of groupId to be put into cache.

@Cacheable(value = GROUP_ID_CACHE, key="#result", unless = "#result == null")
public String getGroupId(String uid) {
    Identity identity = convertUidToBrandId(uid);
    String groupId = convertBrandIdToGroupId(Long.toString(identity.getCustomerId()), identity.getBrand().toUpperCase());
    return groupId;
}

If I do the above , it throws an Illegal Argument exception

:thrown java.lang.IllegalArgumentException(Null key returned for cache operation (maybe you are using named params on classes without debug info?) Builder[public java.lang.String .getGroupId(java.lang.String)] caches=[get-group-id] | key='#result' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='#result == null' | sync='false') from org.springframework.cache.interceptor.CacheAspectSupport

What am I doing wrong here? I tried using CachePut instead of Cacheable- that throws no exceptions, but it doesnt put the result into cache either :(

CacheConfig:

@Configuration
public class CaffeineCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager(GROUP_ID_CACHE);
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine< Object, Object > caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(500)
                .expireAfterAccess(10, TimeUnit.MINUTES)
                .weakKeys()
                .recordStats();
    }
}
ljs
  • 495
  • 1
  • 8
  • 23
  • 1
    I don't know Spring well, but `key="#result"` stands out to me. Since its not known upfront that would be null on entry, right? – Ben Manes Aug 25 '22 at 01:08
  • `"The result of the method call (the value to be cached). Only available in 'unless' expressions and 'cache evict' expression (when beforeInvocation is false)."` ([link](https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/cache.html)) – Ben Manes Aug 25 '22 at 01:13

0 Answers0