Ehcache with Spring Cache assigns wrong key

2019-07-27 03:54发布

I've got a method in UserService:

@Cacheable(value="user", key="#p0")
public User find(String name) {
    return userRepository.findOneByName(name);
}

And it caches. But then I try to get all keys from 'user' cache:

CacheManager cacheManager = CacheManager.getInstance();
cacheManager.getCache("user").getKeys().forEach(o -> log.debug(o.toString()));

Output:

com.cache.domain.User#1

Instead, for example, 'John Doe'.

1条回答
Fickle 薄情
2楼-- · 2019-07-27 04:25

See the Javadoc of getKeys

Returns a list of all elements in the cache, whether or not they are expired.

That's actually returning the elements, no the ids. You may want to change your code to cast o to Element and output getObjectKey() instead.

You don't need to specify the key attribute. Since what you want is to use the single argument of your method (name) the cache abstraction will use that by default.

查看更多
登录 后发表回答