利用AOP实现一个简单的缓存注解

前言

在系统架构层面,缓存是一个经常用到的技术,比如数据库缓存、接口缓存等等。自然在同一层级的应用服务里面也可以用到缓存技术,比如方法A调用方法B,而B是一个运算时间比较久或者是一个需要调用第三方接口获取到数据,那B方法的频繁调用肯定会影响请求的相应速度。对于这类问题也确实有一些解决方案,比如Spring提供的@Cacheable注解。但是看了下这个注解,没发现超时自动清空的属性,查了下别人貌似是用的定时任务实现的,所以就手动实现一个简单版的缓存注解把。

 

@Cacheable注解定义

因为就想实现各简单版的缓存功能,所以@cacheable注解的定义很简单,无非就是key的生成规则以及超时时间

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Cacheable {
    String key(); //缓存的key值

    int[] param() default {}; //影响key的参数

    long timeount() default 1L; //超时时间

    TimeUnit timeUnit() default TimeUnit.SECONDS;  //超时时间单位
}

AOP拦截器

aop提供了一个拦截注解的功能,因此实现起来会比较方便。示例代码使用了ConcurrentHashMap实现本地缓存,不过在实际开发中还是建议使用redis之类的第三方缓存工具。当然,本示例代码有一个很大的问题,那就是无法防止缓存击穿等情况。当然,只是应用在一些简单的方法逻辑上是完全没有问题的。

@Aspect
@Component
public class CacheAspect {

    //缓存map,因为可能多线程调用,所以用ConcurrentHashMap。当然,推荐使用redis等第三方工具来完成缓存功能
    private final Map<String,CacheObject> CACHE = new ConcurrentHashMap<>();

    @Around(value = "@annotation(cacheable)")
    public Object process(ProceedingJoinPoint pjp, Cacheable cacheable) throws Throwable {
        //检查一下注解的参数是否有效
        if (isCacheParamOutOfIndex(cacheable.param(),cacheable.param())){
            return pjp.proceed();
        }
        //根据注解的定义参数和请求方法的参数获得缓存的key值
        String key = getKey(cacheable,cacheable.param(),cacheable.param());

        Object obj = get(key);
        if (obj != null) {
            //如果缓存里有值,则直接返回
            return obj;
        }
        obj = pjp.proceed();
        //记得将结果存入缓存中
        set(key,obj,cacheable.timeount(),cacheable.timeUnit());
        return obj;
    }

    private boolean isCacheParamOutOfIndex(int[] lable, int[] params) {
        for (int index : lable) {
            if (index >= params.length) {
                return true;
            }
        }
        return false;
    }

    private String getKey(Cacheable cacheable, int[] lable, int[] params) {
        StringBuilder builder = new StringBuilder("cache_"+cacheable.key());
        for (int index : lable){
            //不要忘记把参数也加入key
            builder.append("_");
            builder.append(params[index]);
        }

        return builder.toString();

    }

    private void set(String s, Object obj, long timeout, TimeUnit timeUnit) {
        //推荐使用redis等缓存工具实现
        CACHE.put(s,new CacheObject(obj,timeout,timeUnit));
    }

    private Object get(String s) {
        //推荐使用redis等缓存工具实现
        CacheObject cacheObject = CACHE.get(s);
        if (cacheObject == null || cacheObject.isTimeOut())
            return null;
        return cacheObject.getObj();
    }

    /**
     * 内部辅助类
     */
    private class CacheObject{
        private Object obj;

        private long cacheTimeMillis;

        private long timeOutTime;

        private TimeUnit timeUnit;

        CacheObject(Object obj, long timeOutTime, TimeUnit timeUnit) {
            this.obj = obj;
            this.cacheTimeMillis = System.currentTimeMillis();
            this.timeOutTime = timeOutTime;
            this.timeUnit = timeUnit;
        }

        Object getObj() {
            return obj;
        }

        boolean isTimeOut(){
            return System.currentTimeMillis() > cacheTimeMillis + timeUnit.toMillis(timeOutTime);
        }
    }
}

跑一波

测试类

@Component
public class TestClass {
    @Cacheable(key = "key1",param = {0})
    public String test1(String param1) throws InterruptedException {
        System.out.println("重新获得值。。。。test1");
        Thread.sleep(100);
        return String.valueOf(new Random().nextInt());
    }

    @Cacheable(key = "key1",param = {0,1})
    public String test2(String param1,String param2) throws InterruptedException {
        System.out.println("重新获得值。。。。test2");
        Thread.sleep(100);
        return String.valueOf(new Random().nextInt());
    }

    @Cacheable(key = "key2",param = {0,1})
    public String test3(String param1,String param2) throws InterruptedException {
        System.out.println("重新获得值。。。。test3");
        Thread.sleep(100);
        return String.valueOf(new Random().nextInt());
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestClassTest {

    @Autowired
    private TestClass testClass;

    private long t1,t2;

    @Test
    public void test() throws InterruptedException {
        t1 = System.currentTimeMillis();
        System.out.println("获得结果为:"+testClass.test1("111"));
        t2 = System.currentTimeMillis();
        System.out.println("执行时间为:"+(t2 - t1));

        t1 = System.currentTimeMillis();
        System.out.println("获得结果为:"+testClass.test1("111"));
        t2 = System.currentTimeMillis();
        System.out.println("执行时间为:"+(t2 - t1));

        Thread.sleep(1000); //休眠一秒,看缓存是否失效

        t1 = System.currentTimeMillis();
        System.out.println("获得结果为:"+testClass.test1("111"));
        t2 = System.currentTimeMillis();
        System.out.println("执行时间为:"+(t2 - t1));

        //测试两个key相同,参数不同的方法

        t1 = System.currentTimeMillis();
        System.out.println("获得结果为:"+testClass.test2("111","222"));
        t2 = System.currentTimeMillis();
        System.out.println("执行时间为:"+(t2 - t1));

        //测试两个key不同同,参数相同同的方法

        t1 = System.currentTimeMillis();
        System.out.println("获得结果为:"+testClass.test3("111","222"));
        t2 = System.currentTimeMillis();
        System.out.println("执行时间为:"+(t2 - t1));
    }

}

结果

很明显,测试结果和预期结果完全符合

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值