注釈ベースのメソッドキャッシュ

5482 ワード

Webプロジェクトでは、データベースのクエリーに時間がかかるため、同じメソッドの同じパラメータのリクエストは、毎回データベースを調べるのではなくキャッシュに保存する必要があります.メソッドの戻り値はMongodbまたはredisに保存できます.
具体的な実装:
@MethodCache注記
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodCache {
/**
 *          ,   60 
 *
 * @return int
 */
int expireSeconds() default 60;

/**
 *    key,      ,            key
 *
 * @return String
 */
String key() default "";

/**
 *         ,           
 *
 * @return boolean
 */
boolean limitQuery() default true;

/**
 *       
 *
 * @return int
 */
int limitQuerySeconds() default 5;

/**
 *         
 *
 * @return boolean
 */
boolean saveEmptyResult() default true;

}MethodCacheAspect接面
この接面の核心思想は,メソッドの署名+実パラメトリックオブジェクトのハッシュ値をkeyとして,まずキャッシュから取り,取れない場合は具体的なメソッドを呼び出してクエリーし,クエリー結果をキャッシュに保存することであり,そのうち1回に1つのスレッドしか調べられないように設定したり,再試行回数を設定したり,空の結果を保存するかどうかを設定したりすることができる.
@Aspect @Order(value = 2) @Component public class MethodCacheAspect {
@Resource
private JedisPool jedisPool;

@Resource
private DisLockUtil disLockUtil;

private static final Logger LOGGER = LoggerFactory.getLogger(MethodCacheAspect.class);

private static final String EMPTY_RESULT = "NULL";

/**
 *        
 *
 * @param proceedingJoinPoint   
 * @param methodCache           
 * @return Object
 * @throws Throwable     
 */
@Around("@annotation(methodCache)")
public Object execute(ProceedingJoinPoint proceedingJoinPoint, MethodCache methodCache) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = methodSignature.getMethod();

    //       
    int size = proceedingJoinPoint.getArgs().length;
    //       
    List list = parseRequestParam(proceedingJoinPoint, size);
    //          key
    String key = methodCache.key();
    if (StringUtils.isBlank(key)) {
        key = getSignature(method);
    }
    key += HashAlgorithms.mixHash(JSON.toJSONString(list));
    Object deserialize = tryGetFromCache(key);
    if (deserialize != null) {
        //       ,                  ,          DB 
        if (EMPTY_RESULT.equals(deserialize)) {
            return null;
        }
        return deserialize;
    }
    Object proceed;
    String mutexKey = "mutex_" + key;
    if (methodCache.limitQuery()) {
        boolean lock = disLockUtil.lock(mutexKey, methodCache.limitQuerySeconds());
        //              ,         
        int count = 1;
        while (!lock && count < 3) {
            lock = disLockUtil.lock(mutexKey, methodCache.limitQuerySeconds());
            count++;
            TimeUnit.SECONDS.sleep(1);
        }
        if (lock) {
            //     
            proceed = executeConcreteMethod(proceedingJoinPoint, mutexKey);
            Object cacheResult = proceed;
            //       ,         
            if (cacheResult == null) {
                cacheResult = EMPTY_RESULT;
            }
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.setnx(key.getBytes(), KryoUtil.writeToByteArray(cacheResult));
                jedis.expire(key, methodCache.expireSeconds());
            }
        } else {
            LOGGER.warn("        , key :{}", mutexKey);
            throw new CustomException(ErrorCodeEnum.DUPLICATE_REQUEST.getMessage());
        }
    } else {
        //     
        proceed = executeConcreteMethod(proceedingJoinPoint, mutexKey);
    }
    return proceed;
}

/**
 *        
 *
 * @param proceedingJoinPoint   
 * @return Object
 * @throws Throwable   
 */
private Object executeConcreteMethod(ProceedingJoinPoint proceedingJoinPoint, String mutexKey) throws Throwable {
    Object proceed;
    try {
        proceed = proceedingJoinPoint.proceed();
    } finally {
        disLockUtil.unlock(mutexKey, false);
    }
    return proceed;
}

/**
 *         
 *
 * @param key key
 * @return Object
 */
private Object tryGetFromCache(String key) {
    byte[] resultBytes;
    try (Jedis jedis = jedisPool.getResource()) {
        if (!jedis.exists(key)) {
            return null;
        }
        resultBytes = jedis.get(key.getBytes());
    }
    if (resultBytes != null) {
        LOGGER.info("key:{}     ", key);
        return KryoUtil.readFromByteArray(resultBytes);
    }
    return null;
}

/**
 *       
 *
 * @param proceedingJoinPoint   
 * @param size     
 * @return List
 */
private List parseRequestParam(ProceedingJoinPoint proceedingJoinPoint, int size) {
    Object[] args = proceedingJoinPoint.getArgs();
    List argList = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        if (args[i] instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) args[i];
            argList.add(request.getParameterMap());
        } else if (args[i] instanceof HttpServletResponse || args[i] instanceof HttpSession
                || args[i] instanceof HttpCookie) {
            continue;
        } else {
            argList.add(args[i]);
        }
    }
    return argList;
}

/**
 *       
 *
 * @param method   
 * @return String
 */
private String getSignature(Method method) {
    StringBuilder sb = new StringBuilder();
    String methodName = method.getName();
    if (StringUtils.isNotBlank(methodName)) {
        sb.append(method).append("#");
    }
    return sb.toString();
}

}