Spring Cache annotation cacheable, the main parameter description:
- value is CacheName, when the Ehcache is integrated, a cache,cache is created in that name to store the different key-value.
- key, the unique identifier of the cached object, when integrated with Redis, key definitions need to be strictly differentiated and cannot be defined simply by a variable, because CacheName does not play a role in differentiating the cache.
- Keygenerator The custom key value generator, there will be a demo implementation below.
- CacheManager Selects the specified cache manager, typically using the default manager, which does not require special designation,
- cacheresolver defines how to access the cache list, the default Simplecacheresolver implementation, Namedcacheresolver is also more common.
- condition data that satisfies the cache condition (spel expression) is placed in the cache, and condition is judged before and after the method is called.
- unless used to veto cache updates, spel expressions that differ from condition,unless are only judged after the method executes
The following is an example of Redis integration, which describes key usage.
Custom Keygenerator
@Bean public KeyGenerator myKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); sb.append("("); for (Object param : params) { sb.append(param.toString()); sb.append(","); } sb.append(")"); return sb.toString(); } }; }
Fixed key example
@Cacheable(value = CacheConsts.MASTER_SYSTEMCONFIG_CACHE_KEY, key = "‘SYSTEMCONFIG_MAP‘") public Map<String, SystemConfigDto> loadSystemConfigMap() {
Variable Key Example
@Cacheable(value = CacheConsts.WS_FILTER_TIME_KEY, key = CacheConsts.WS_FILTER_TIME_KEY + "#appId") public List<WsTimeFilterDto> loadByAppId(String appId) {
@Cacheable(value = CacheConsts.MASTER_CITY_CACHE_KEY, key = CacheConsts.MASTER_CITY_CACHE_KEY + "#exchangeRateEntity.currency") public List<ExchangeRateEntity> loadExchangeRate(ExchangeRateEntity exchangeRateEntity) {
Custom Key Example
@Cacheable(value = CacheConsts.WS_PRICE_RULE_KEY, keyGenerator = "myKeyGenerator")
condition Example
@Cacheable(value = CacheConsts.MASTER_CITY_CACHE_KEY, key = CacheConsts.MASTER_CITY_CACHE_KEY + "#exchangeRateEntity.currency",condition = "#exchangeRateEntity.currency ne ‘CNY‘ ") public List<ExchangeRateEntity> loadExchangeRate(ExchangeRateEntity exchangeRateEntity) {
The definition and application of Spring cachable key