05. spring 缓存

在spring boot中监控缓存命中率
https://segmentfault.com/a/1190000011129505

spring boot cache整合redis
https://www.cnblogs.com/imyijie/p/6518547.html

spring cache 使用详解以及一些概念(TTL, TTI)
http://jinnianshilongnian.iteye.com/blog/2001040

spring cache中使用复杂的key
http://www.iteye.com/topic/1123633

多级缓存的实现
https://www.jianshu.com/p/ef9042c068fd

spring cache官网
https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-annotations-cacheable-default-key

如果使用spring cache, 那么它的key的使用就是个重点

如果是复杂的查询需要使用缓存,最好使用自定key生成方式:
例如:

package org.pzy.support.cache;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import com.alibaba.fastjson.JSON;
import org.pzy.support.util.Encryptor;
import lombok.extern.log4j.Log4j;

@Component("customeKeyGenerator")
@Log4j
public class CacheKeyGenerator implements KeyGenerator {

  public static final int NO_PARAM_KEY = 0;
  public static final int NULL_PARAM_KEY = 53;

  @Override
  public Object generate(Object target, Method method, Object... params) {
    StringBuilder key = new StringBuilder();
    key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
    if (params.length == 0) {
      return key.append(NO_PARAM_KEY).toString();
    }
    for (Object param : params) {
      if (param == null) {
        log.warn("input null param for Spring cache, use default key=" + NULL_PARAM_KEY);
        key.append(NULL_PARAM_KEY);
      } else if (ClassUtils.isPrimitiveArray(param.getClass())) {
        int length = Array.getLength(param);
        for (int i = 0; i < length; i++) {
          key.append(Array.get(param, i));
          key.append(',');
        }
      } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
        key.append(param);
      } else {
        log.warn("Using an object as a cache key may lead to unexpected results. "
            + "Either use @Cacheable(key=..) or implement CacheKey. Method is " + target.getClass()
            + "#" + method.getName());
        key.append(JSON.toJSONString(param));
      }
      key.append('-');
    }
    String finalKey = Encryptor.md5(key.toString());
    log.debug("finalKey: " + finalKey);

    return finalKey;
  }

}
   // customeKeyGenerator就是那个自定义key生成类的bean的名称
  @Cacheable(keyGenerator="customeKeyGenerator")
  @Override
  public List statisticsManualBizListData(CmbBizCriteria criteria, boolean splitPage) {}

你可能感兴趣的:(05. spring 缓存)