怎么在springboot中使用GuavaCache處理緩存?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供牙克石網(wǎng)站建設(shè)、牙克石做網(wǎng)站、牙克石網(wǎng)站設(shè)計(jì)、牙克石網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、牙克石企業(yè)網(wǎng)站模板建站服務(wù),十載牙克石做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
使用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取得參數(shù),根據(jù)參數(shù)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); } }
看完上述內(nèi)容,你們掌握怎么在springboot中使用GuavaCache處理緩存的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!