LocalCacheAspect.java 1.3 KB
package com.viontech.fanxing.commons.aop;

import com.viontech.fanxing.commons.base.LocalCache;
import com.viontech.fanxing.commons.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * .
 *
 * @author 谢明辉
 * @date 2021/9/9
 */

@Component
@Aspect
@Slf4j
public class LocalCacheAspect {

    @Around("@annotation(localCache)")
    public Object around(ProceedingJoinPoint point, LocalCache localCache) throws Throwable {

        try {
            ImmutablePair<Boolean, Object> cacheResult = CacheUtil.get(localCache.value());
            Boolean exists = cacheResult.left;
            Object o;
            if (exists && cacheResult.right != null) {
                o = cacheResult.right;
            } else {
                o = point.proceed();
                CacheUtil.cache(localCache.value(), o, localCache.timeunit(), localCache.duration());
            }
            return o;
        } catch (RuntimeException e) {
            log.error("缓存调用方法:{}", point.toLongString());
            log.error("缓存出错", e);
        }
        return point.proceed();
    }

}