今天嘗試了一下springboot集成springcache做緩存,springcache是基於annotation(注釋)的一個緩存技術
特點總結如下:
- 通過少量的配置 annotation 注釋即可使得既有代碼支持緩存
- 支持開箱即用 Out-Of-The-Box,即不用安裝和部署額外第三方組件即可使用緩存
- 支持 Spring Express Language,能使用對象的任何屬性或者方法來定義緩存的 key 和 condition
- 支持 AspectJ,並通過其實現任何方法的緩存支持
- 支持自定義 key 和自定義緩存管理者,具有相當的靈活性和擴展性
使用起來也非常的簡單
第一步:添加maven依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
第二步:新建一個TestTime類
import java.util.Date; public class TestTime { private Date time; public TestTime(Date time){ this.time=time; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @Override public String toString() { return "{ 時間='" + time + '\'' + '}'; } }
第三步,再添加一個TestTime接口
import hello.entity.TestTime; public interface TestTimeService { TestTime getTestTime(); }
第四步,到主函數添加:
@EnableCaching
開啟緩存,這個非常重要
第五步,實現該接口:
import hello.Service.TestTimeService; import hello.entity.TestTime; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.util.Date; @Component public class TestTimeController implements TestTimeService { @Override @Cacheable(value = "time") public TestTime getTestTime(){ return new TestTime(new Date()); } }
使用@Cachable就可以使用緩存了,非常簡單。
關於緩存注解的仔細介紹可以參考文章:https://www.cnblogs.com/fashflying/p/6908028.html
第六步,創建一個測試類TestRun:
import hello.Service.TestTimeService; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class TestRun { private static final Logger log = LoggerFactory.getLogger(TestRun.class); @Autowired TestTimeService testTimeService; @Test public void getTime() throws InterruptedException { int i = 1; while (i <= 20) { log.info("" + "第" + i + "次獲取時間" + testTimeService.getTestTime()); i++; Thread.sleep(1000); } } }
創建的目錄如下:
最后:運行getTime測試方法:
可以看到,20次去調用gettesttime,獲取的並不是最新的時間,而是緩存內的時間。
本文源碼:https://gitee.com/Hiro-D/Java/tree/master/Spring-cache
直接使用springcahce是無法設置緩存有效時間的,是要使用ehcache或者redis 或者guava設置,下篇講一下springcahce設置過期時間。