springboot2.3.4集成EhCache缓存框架完整代码
生活随笔
收集整理的這篇文章主要介紹了
springboot2.3.4集成EhCache缓存框架完整代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼部分
pom
<?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.zxl.ehcache</groupId><artifactId>springboot-ehcache-demo</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.10</version><scope>provided</scope></dependency><!-- Spring Boot 緩存支持啟動器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!-- Ehcache 坐標 --><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.5.5</version></plugin></plugins></build></project>啟動類
package com.zxl.ehcache;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching;/* * 在啟動類前加上@EnableCaching注解;這樣的話,啟動類啟動時會去啟動緩存啟動器 * */ @SpringBootApplication @EnableCaching public class CacheApplication {public static void main(String[] args) {SpringApplication.run(CacheApplication.class, args);}}controller
package com.zxl.ehcache.controller;import com.zxl.ehcache.model.ProductInfo; import com.zxl.ehcache.service.CacheService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;/*** 緩存Controller** @author zxl*/ @RestController public class CacheController {@Autowiredprivate CacheService cacheService;@PostMapping("/testPutCache")public String testPutCache(@RequestBody ProductInfo productInfo) {cacheService.saveLocalCache(productInfo);return "success";}@GetMapping("/testGetCache")public ProductInfo testGetCache(Long id) {return cacheService.getLocalCache(id);}}model
package com.zxl.ehcache.model;import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;import java.io.Serializable;/*** 實體類實現可序列化接口Serializable;由于需要實體類支持緩存中的磁盤存儲,所以需要實體類實現可序列化接口** @author zxl*/ @Data @NoArgsConstructor @AllArgsConstructor public class ProductInfo implements Serializable {private Long id;private String name;private Double price; }service
package com.zxl.ehcache.service;import com.zxl.ehcache.model.ProductInfo ;/*** 緩存service接口* @author zxl**/ public interface CacheService {/*** 將商品信息保存到本地緩存中* @param productInfo* @return*/ProductInfo saveLocalCache(ProductInfo productInfo);/*** 從本地緩存中獲取商品信息* @param id* @return*/ProductInfo getLocalCache(Long id);}impl:
package com.zxl.ehcache.service.impl;import com.zxl.ehcache.model.ProductInfo; import com.zxl.ehcache.service.CacheService; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service;/*** 緩存Service實現類* 使用@CachePut存數據到緩存* 使用@Cacheable讀取緩存* @author zxl*/ @Service public class CacheServiceImpl implements CacheService {public static final String CACHE_NAME = "local";/*** 將商品信息保存到本地緩存中** @param productInfo* @return*/@CachePut(value = CACHE_NAME, key = "'key_'+#productInfo.getId()")public ProductInfo saveLocalCache(ProductInfo productInfo) {return productInfo;}/*** 從本地緩存中獲取商品信息** @param id* @return*/@Cacheable(value = CACHE_NAME, key = "'key_'+#id")public ProductInfo getLocalCache(Long id) {return null;}// 使用@CacheEvict清除緩存/*@CacheEvict(value="users",allEntries=true)public void saveUsers(Users users) {this.usersRepository.save(users);}*/// @CacheEvict是用來標注在需要清除緩存元素的方法或類上的。當標記在一個類上時表示其中所有的方法的執行都會觸發緩存的清除操作。@CacheEvict可以指定的屬性有value、key、condition、allEntries和beforeInvocation。// 其中value、key和condition的語義與@Cacheable對應的屬性類似;allEntries是boolean類型,表示是否需要清除緩存中的所有元素。默認為false,表示不需要。// 當指定了allEntries為true時,Spring Cache將忽略指定的key。有的時候我們需要Cache一下清除所有的元素,這比一個一個清除元素更有效率// 使用@CachePut標注的方法在執行前不會去檢查緩存中是否存在之前執行過的結果,而是每次都會執行該方法,并將執行結果以鍵值對的形式存入指定的緩存中。// @Cacheable:類或者方法上,類代表所有的方法都使用它,方法上針對特定的方法,作用就是先查詢緩存是否有值,有的話就直接返回緩存結果}配置文件
application.yml
server:port: 8080spring:cache:type: ehcacheehcache:config: classpath:ehcache.xmlehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false"><!-- diskStore:ehcache其實是支持內存+磁盤+堆外內存,幾個層級的緩存 --><!-- 在這里設置一下,但是一般不用的 --><diskStore path="java.io.tmpdir/Tmp_EhCache" /><!-- defaultCache,是默認的緩存策略 --><!-- 如果你指定的緩存策略沒有找到,那么就用這個默認的緩存策略 --><!-- external:如果設置為true的話,那么timeout就沒有效果,緩存就會一直存在,一般默認就是false --><!-- maxElementsInMemory:內存中可以緩存多少個緩存條目,在實踐中,你是需要自己去計算的,比如你計算你要緩存的對象是什么?有多大?最多可以緩存多少MB,或者多少個G的數據?除以每個對象的大小,計算出最多可以放多少個對象 --><!-- overflowToDisk:如果內存不夠的時候,是否溢出到磁盤 --><!-- diskPersistent:是否啟用磁盤持久化的機制,在jvm崩潰的時候和重啟之間,不用 --><!-- timeToIdleSeconds:對象最大的閑置的時間,如果超出閑置的時間,可能就會過期,我們這里就不用了,緩存最多閑置5分鐘就被干掉了 --><!-- timeToLiveSeconds:對象最多存活的時間,我們這里也不用,超過這個時間,緩存就過期,就沒了 --><!-- memoryStoreEvictionPolicy:當緩存數量達到了最大的指定條目數的時候,需要采用一定的算法,從緩存中清除一批數據,LRU,最近最少使用算法,最近一段時間內,最少使用的那些數據,就被干掉了 --><defaultCacheeternal="false"maxElementsInMemory="1000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="300"timeToLiveSeconds="0"memoryStoreEvictionPolicy="LRU" /><!-- 手動指定的緩存策略 --><!-- 比如你一個應用吧,可能要緩存很多種不同的數據,比如說商品信息,或者是其他的一些數據 --><!-- 對不同的數據,緩存策略可以在這里配置多種 --><cachename="local"eternal="false"maxElementsInMemory="1000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="300"timeToLiveSeconds="0"memoryStoreEvictionPolicy="LRU" /><!-- ehcache這種東西,簡單實用,是很快速的,1小時上手可以用在項目里了,沒什么難度的 --><!-- ehcache這個技術,如果講深了,里面的東西還是很多的,高級的feature,但是我們這里就不涉及了 --></ehcache>測試
@Cacheable(value = CACHE_NAME, key = “‘key_’+#id”)
public ProductInfo getLocalCache(Long id) {
return null;
}
可以看到返回的是null,但是依然可以查詢到數據,就說明是從緩存中獲取到的
總結
以上是生活随笔為你收集整理的springboot2.3.4集成EhCache缓存框架完整代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux curl发送POST请求
- 下一篇: Java反射基础:获取Class对象的三