Caching Data in Spring Using Redis · caseyscarborough.com
Implementing a Custom Key Generator
For basic purposes, the default key generation system for cached data works. The parameters to your method become the key in your cache store. For example, in the following method, the value for the parameter username
would become the key in your store:
@Cacheable("users") public User findByUsername(String username)
But this becomes problematic when you want cache the result of another method that also takes in the same value, for instance:
@Cacheable("users") public Integer getLoginCountByUsername(String username)
You could easily just specify a different key for each @Cacheable
annotation, but that becomes tedious and hard to maintain. The solution is to implement a custom key generator that will generate the key for each method to be unique by default. Adding a keyGenerator
bean to your CacheConfig
class (shown above) will give you this functionality. Note that for your custom key generator to work by default, this class must implement the CachingConfigurer
interface. Extending CachingConfigurerSupport
will provide this for you.
Read full article from Caching Data in Spring Using Redis · caseyscarborough.com
No comments:
Post a Comment