如果同时使用多种切片实现可能造成冲突错误

依赖

spring环境

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.7.14</version>
            </dependency>

使用示例

    //带有注解并写入key,即可自动带有缓存功能
    @MemCache(key="getTimeNow")
    public String getTimeNow(String title,Integer num){
        System.out.println(title + num);
        return DateTime.now().toString();
    }

注解类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MemCache {
    String key();
}

切片类

@Aspect
@Component
public class MemCacheAspect {
    @Resource
    CacheUtil cacheUtil;
    /**
     * 定义切点
     * MemCache注解切点
     */
    @Pointcut("@annotation(com.....util.MemCache)")
    public void doMemCache() {
    }

    @Around("doMemCache()")
    public Object doAround(ProceedingJoinPoint pjd) {
        Method method = ((MethodSignature) pjd.getSignature()).getMethod();
        MemCache memCache = method.getAnnotation(MemCache.class);
        String cacheKey = makeKey(memCache.key(), pjd.getArgs());
        Object cacheObj = cacheUtil.get(cacheKey);
        if (cacheObj != null) {
            log.info("命中缓存,key:{}", cacheKey);
            return cacheObj;
        }
        Object resultObj = null;
        try {
            resultObj = pjd.proceed();
        } catch (Throwable throwable) {
            log.error("缓存切片错误", throwable);
        }
        cacheUtil.put(cacheKey, resultObj);
        return resultObj;
    }

    /**
     * 构造缓存key
     */
    public String makeKey(String key, Object[] args){
        StringBuilder keyRet = new StringBuilder();
        for (Object obj: args) {
            keyRet.append("_").append(obj.toString());
        }
        return key + keyRet;
    }
}

缓存类

@Component
public class CacheUtil {
    /**
     * 最大缓存时间
     * 4h
     */
    private final int CACHE_MAX_TIME = 4 * 3600 * 1000;
    /**
     * 缓存对象
     */
    private final TimedCache<String, Object> cache = cn.hutool.cache.CacheUtil.newTimedCache(CACHE_MAX_TIME);
    CacheUtil(){
        //1小时清理一次缓存
        cache.schedulePrune(3600 * 1000);
    }
    public Object get(String key){
        return cache.get(key, false);
    }

    public void put(String key, Object obj){
        cache.put(key, obj);
    }
}
最后修改:2021 年 12 月 02 日
如果觉得我的文章对你有用,请随意赞赏