springboot使用GuavaCache做简单缓存处理的方法
问题背景
实际项目碰到一个上游服务商接口有10秒的查询限制(同个账号)。
项目中有一个需求是要实时统计一些数据,一个应用下可能有多个相同的账号。由于服务商接口的限制,当批量查询时,可能出现同一个账号第一次查询有数据,但第二次查询无数据的情况。
解决方案
基于以上问题,提出用缓存的过期时间来解决。
这时,可用Redis和GuavaCache来解决:
当批量查询时,同一个账号第一次查询有数据则缓存并设置过期时间10s,后续查询时直接从缓存中取,没有再从服务商查询。
最终采用GuavaCache来解决,原因是:
- 应用是部署单台的,不会有分布式的问题
- Redis虽然可以实现,但会有通讯时间消耗
- GuavaCache使用本地缓存,支持并发
使用GuavaCache可以快速建立缓存
1.需要在启动类上注解@EnableCaching
2.配置CacheManager
3.控制器上注解使用@Cacheable
pom.xml
org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework spring-context-support 4.3.9.RELEASE com.google.guava guava 18.0 org.apache.maven.plugins maven-compiler-plugin 1.8 UTF-8
CacheConfig.java配置类
packageapplication.config; importcom.google.common.cache.CacheBuilder; importorg.springframework.cache.CacheManager; importorg.springframework.cache.guava.GuavaCache; importorg.springframework.cache.support.SimpleCacheManager; importorg.springframework.context.annotation.Configuration; importjava.util.ArrayList; importjava.util.List; importjava.util.concurrent.TimeUnit; @Configuration publicclassCacheConfig{ publicCacheManagercacheManager(){ GuavaCacheguavaCache=newGuavaCache("GuavaCacheAll",CacheBuilder.newBuilder() .recordStats() .expireAfterWrite(10000,TimeUnit.SECONDS) .build()); Listlist=newArrayList(); list.add(guavaCache); SimpleCacheManagersimpleCacheManager=newSimpleCacheManager(); simpleCacheManager.setCaches(list); returnsimpleCacheManager; } }
TestController.java控制器测试类
packageapplication.controller; importorg.springframework.cache.annotation.Cacheable; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RestController; @RestController publicclassTestController{ @RequestMapping("/test") //key是使用spEl取得参数,根据参数name作为缓存的key,value是使用的缓存list中的那个,具体看配置类 @Cacheable(value="GuavaCacheAll",key="#name") publicStringtt(Stringname){ System.out.println("intt"); return"name:"+name; } }
Application.javaspringboot启动类
packageapplication; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching publicclassApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(Application.class,args); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。