如何用一行代码使API提速几十倍

annocache

介绍

annocache-spring-boot-starter是一个超轻量级的注解式缓存组件。
只需要一行代码,即可实现方法返回值的自动化缓存,让方法的数据返回时间降为毫秒级,访问速度提升几十倍。

特色

1.和Spring提供的注解式缓存组件相比,使用方式和配置参数更加简便。只有一个方法注解@AnnoCache,代表启用缓存;注解上只有一个参数seconds,代表缓存数据的过期时长秒数。

2.具备自动二级缓存功能,一定程度上可以避免缓存击穿。当缓存失效时,使用一个线程执行业务代码进行缓存内容的更新,其余并发访问线程则从二级缓存获取最后一个版本的缓存值先返给前端。

使用说明

参考示例项目annocache-sample-api,这是一个简单的基于SpringBoot创建的web项目。

1.项目的pom.xml中增加依赖。

   	<dependency>
   		<groupId>com.gitee.cs_liwei</groupId>
   		<artifactId>annocache-spring-boot-starter</artifactId>
   		<version>0.0.1-SNAPSHOT</version>
   	</dependency>

2.目前支持Redis缓存方式,需在application.yml中指定Redis服务器的地址和端口。

spring:
  redis:
    cluster:
      - localhost:6379
      - localhost:6379

示例中采用的是本地启动的Redis服务器 localhost:6379。

如果开发机采用的是Windows操作系统,可以从 这里 下载Redis Server的Windows版本,做本地启动测试。

3.在需要缓存的业务方法上,简单的添加 @AnnoCache(seconds = 45) 注解代码即可实现功能。seconds为缓存时长,单位为秒。

/**
 * dummy business
 */
@Component
public class TestBusiness {

    @AnnoCache(seconds = 45)
    public TestModel test(int param1, Integer param2, String param3){
        TestModel model = new TestModel();
        //...
        //dummy process time cost(1000 milliseconds)
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return model;
    }
}

4.调用业务方法的地方,将会启用缓存。

@RestController
public class TestController {
    @Autowired
    TestBusiness testBusiness;

    @RequestMapping("/test1")
    public TestModel test(@RequestParam int param1,
                          @RequestParam Integer param2,
                          @RequestParam String param3){

        //business process method with cache annotation.
        //the dummy process will cost over 1 second if no cache.
        return testBusiness.test(param1, param2, param3);
    }
}

5.启动annocache-sample-api项目,在本地浏览器中访问:

http://localhost:8080/test1?param1=1&param2=2&param3=3

可以观察到,没有建立缓存的时候API返回耗时约1000毫秒以上,建立缓存后则缩短为20毫秒以内。

注意点

1.添加缓存注解的方法,其参数不可为实体类型。所有参数都会参与缓存Key的构建,因此建议都使用String或基本类型。实际上,坚持采用简单类型的入参,也更加符合Java编码的最佳实践。

2.可以缓存的返回值类型,目前已支持Object实体,List以及Map,序列化方式为Jackson。

@Component
public class TestBusiness {
    @AnnoCache(seconds = 45)
    public List<TestModel>  test2(int param1, Integer param2, String param3){
        List<TestModel> list = new ArrayList<>();
        //...
        return list;
    }

    @AnnoCache(seconds = 45)
    public Map<String, TestModel> test3(int param1, Integer param2, String param3){
        Map<String, TestModel> map = new HashMap<>();
        //...
        return map;
    }
}

TODO

1.内存缓存的支持。

2.Redis服务不可用等情况下的监控与降级。

3.其他可以性能优化的点。

代码GIT地址:

https://gitee.com/cs_liwei/annocache
https://github.com/liwei0705/annocache

posted @ 2021-09-29 15:35  cs_liwei  阅读(160)  评论(0编辑  收藏  举报