怎么在springboot中使用GuavaCache处理缓存
怎么在springboot中使用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 配置类
package application.config; import com.google.common.cache.CacheBuilder; import org.springframework.cache.CacheManager; import org.springframework.cache.guava.GuavaCache; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Configuration public class CacheConfig { public CacheManager cacheManager(){ GuavaCache guavaCache = new GuavaCache("GuavaCacheAll", CacheBuilder.newBuilder() .recordStats() .expireAfterWrite(10000, TimeUnit.SECONDS) .build()); List list = new ArrayList(); list.add(guavaCache); SimpleCacheManager simpleCacheManager = new SimpleCacheManager(); simpleCacheManager.setCaches(list); return simpleCacheManager; } }
TestController.java 控制器测试类
package application.controller; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @RequestMapping("/test") //key是使用spEl取得参数,根据参数name作为缓存的key,value是使用的缓存list中的那个,具体看配置类 @Cacheable(value = "GuavaCacheAll",key = "#name") public String tt(String name){ System.out.println("in tt"); return "name:"+name; } }
Application.java springboot启动类
package application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
看完上述内容,你们掌握怎么在springboot中使用GuavaCache处理缓存的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
当前名称:怎么在springboot中使用GuavaCache处理缓存
网页地址:http://cdiso.cn/article/ishdjs.html