本文講解Spring Boot與EhCache的整合。java
EhCache 是一個純Java的進程內緩存框架,具備快速、精幹等特色,是Hibernate中默認CacheProvider。Ehcache是一種普遍使用的開源Java分佈式緩存。主要面向通用緩存,Java EE和輕量級容器。它具備內存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特色。web
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiidian</groupId> <artifactId>ch03_10_springboot_ehcache</artifactId> <version>1.0-SNAPSHOT</version> <!-- 導入springboot父工程. 注意:任何的SpringBoot工程都必須有的!!! --> <!-- 父工程的做用:鎖定起步的依賴的版本號,並無真正到依賴 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.11.RELEASE</version> </parent> <dependencies> <!--web起步依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--springboot 集成 junit 起步依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.1.6.RELEASE</version> <scope>test</scope> </dependency> <!-- 緩存座標 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>2.1.11.RELEASE</version> </dependency> <!-- Ehcache支持 --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.6</version> </dependency> </dependencies> </project>
在resources目錄下創建ehcache.xml,內容以下:spring
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <!-- defaultCache: 默認配置 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <!-- 緩存名稱爲customer的配置 --> <cache name="customer" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </cache> </ehcache>
參數說明:apache
#配置EhCache的配置 spring: cache: ehcache: config: ehcache.xml # 讀取ehcache.xml配置
package com.yiidian; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; /** * Spring Boot引導類 * 一點教程網 - www.yiidian.com */ @SpringBootApplication @EnableCaching // 開啓緩存 public class MyBootApplication { public static void main(String[] args) { SpringApplication.run(MyBootApplication.class,args); } }
引導類中須要添加@EnableCaching註解,開啓緩存功能api
package com.yiidian.service; import com.yiidian.domain.Customer; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; /** * 業務層 *一點教程網 - www.yiidian.com */ @Service public class CustomerService { @Cacheable(value = "customer",key = "#id") public Customer findById(Integer id){ System.out.println("執行了UserService獲取User"); Customer customer = new Customer(); customer.setId(1); customer.setName("小明"); customer.setGender("男"); customer.setTelephone("13244445555"); return customer; } }
@Cacheable的屬性:緩存
package com.yiidian.test; import com.yiidian.MyBootApplication; import com.yiidian.service.CustomerService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * SpringBoot整合EhCache * 一點教程網 - www.yiidian.com */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MyBootApplication.class) public class EhCacheDemo { @Autowired private CustomerService customerService; @Test public void test1(){ //查詢第一次 System.out.println(customerService.findById(1)); //查詢第二次 System.out.println(customerService.findById(1)); } }
從結果能夠看出,第一次調用Service的時候,到Service內部獲取數據。可是第二次調用Service時已經不須要從Service獲取數據,證實第一次查詢的時候已經把Customer對象緩存到EhCache中。springboot
@Cacheable/@CachePut/@CacheEvict 主要的參數:微信
@Cacheable註解會先查詢是否已經有緩存,有會使用緩存,沒有則會執行方法並緩存。app
@Cacheable(value = "customer" ,key = "targetClass + methodName +#p0") public List<Customer> queryAll(Customer cust) { return customerDao.findAllByUid(cust); }
當咱們須要緩存的地方愈來愈多,你可使用@CacheConfig(cacheNames = {"myCache"})註解來統一指定value的值,這時可省略value,若是你在你的方法依舊寫上了value,那麼依然以方法的value值爲準。框架
使用方法以下:
@CacheConfig(cacheNames = {"myCache"}) public class UserServiceImpl implements UserService { @Override @Cacheable(key = "targetClass + methodName +#p0")//此處沒寫value public List<BotRelation> findUsers(int num) { return userDao.findUsers(num); } ..... }
@CachePut註解的做用 主要針對方法配置,可以根據方法的請求參數對其結果進行緩存,和 @Cacheable 不一樣的是,它每次都會觸發真實方法的調用 。簡單來講就是用戶更新緩存數據。但須要注意的是該註解的value 和 key 必須與要更新的緩存相同,也就是與@Cacheable 相同。示例:
@CachePut(value = "customer", key = "targetClass + #p0") public Customer updata(Customer cust) { Customer customer = customerDao.findAllById(cust.getId()); customer.updata(cust); return customer ; } @Cacheable(value = "customer", key = "targetClass +#p0")//清空緩存 public Customer save(Customer cust) { customerDao.save(cust); return cust; }
@CachEvict 的做用 主要針對方法配置,可以根據必定的條件對緩存進行清空 。
@Cacheable(value = "customer",key = "#p0.id") public Customer save(Customer cust) { customerDao.save(cust); return job; } //清除一條緩存,key爲要清空的數據 @CacheEvict(value="customer",key="#id") public void delect(int id) { customerDao.deleteAllById(id); } //方法調用後清空全部緩存 @CacheEvict(value="customerCache",allEntries=true) public void delectAll() { customerDao.deleteAll(); } //方法調用前清空全部緩存 @CacheEvict(value="customerCache",beforeInvocation=true) public void delectAll() { customerDao.deleteAll(); }
本文首發微信公衆號:一點教程。歡迎關注公衆號,得到獨家整理的學習資源和平常乾貨推送。 若是您對個人系列教程感興趣,也能夠關注個人網站:yiidian.com