springboot 整合緩存(Ehcache或者reids)


這里介紹Spring Boot結合JPA,MySQL和Ehcache實現緩存功能,提高程序訪問效率。

一、Maven依賴

  

<!-- caching -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

二、程序的啟動類加上 @EnableCaching

3、application.yml和ehcache.xml配置文件 

application.yml
#使用ehcache緩存配置
spring:
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<cache name="sysCache"
maxElementsInMemory="100000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
memoryStoreEvictionPolicy="LRU"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
4、使用 

注意:
1)@CacheConfig(cacheNames = {“lemonCache”})設置了ehcache的名稱,這個名稱就是ehcache.xml內的名稱; (可以不指定,應為在yml 中已經制定了)
2)@Cacheable:應用到讀取數據的方法上,即可緩存的方法,如查找方法:先從緩存中讀取,如果沒有再調 用方法獲取數據,然后把數據添加到緩存中,適用於查找;
3)@CachePut:主要針對方法配置,能夠根據方法的請求參數對其結果進行緩存,和 @Cacheable 不同的是,它每次都會觸發真實方法的調用。適用於更新和插入;
4)@CacheEvict:主要針對方法配置,能夠根據一定的條件對緩存進行清空。適用於刪除。

整合reids   https://blog.csdn.net/plei_yue/article/details/79362372


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM