<?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"> <!-- 該文件存放在resources目錄下 application.properties文件添加spring.cache.ehcache.config=classpath:/ehcache.xml diskStore:為緩存路徑,ehcache分為內存和磁盤兩級,此屬性定義磁盤的緩存位置。參數解釋如下: user.home – 用戶主目錄 user.dir – 用戶當前工作目錄 java.io.tmpdir – 默認臨時文件路徑 --> <diskStore path="java.io.tmpdir/Tmp_EhCache"/> <!-- defaultCache:默認緩存策略,當ehcache找不到定義的緩存時,則使用這個緩存策略。只能定義一個。 --> <!-- name:緩存名稱。 maxElementsInMemory:緩存最大數目 maxElementsOnDisk:硬盤最大緩存個數。 eternal:對象是否永久有效,一但設置了,timeout將不起作用。 overflowToDisk:是否保存到磁盤,當系統當機時 timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。 timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。 diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。 diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。 memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。 clearOnFlush:內存數量最大時是否清除。 memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。 FIFO,first in first out,這個是大家最熟的,先進先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。 LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。 --> <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="259200" memoryStoreEvictionPolicy="LRU"/> <cache name="product" eternal="false" maxElementsInMemory="5000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LRU"/> </ehcache>
package ehcache.demo.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import ehcache.demo.entity.Product; import ehcache.demo.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.sound.midi.Soundbank; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class ProductController { @Autowired private ProductService productService; /** * 獲取所有商品 使用redis緩存 * * @return */ @SuppressWarnings("unchecked") @RequestMapping("getall") @ResponseBody public Object GetAllProduct() { /**************** 高並發環境下的緩存穿透測試 **********************/ /* // 線程,該線程調用底層的查詢所有商品方法 Runnable runnable = new Runnable() { public void run() { productService.getAll(); } }; // 模擬多線程測試高並發穿透問題 ExecutorService executorService = Executors.newFixedThreadPool(6); for (int i = 0; i < 1000; i++) { executorService.submit(runnable); } */ return productService.getAll(); } /** * 獲取分頁商品 * * @return */ @RequestMapping("getpage") @ResponseBody public Object GetPage() { // 分頁查詢 PageHelper.startPage(1, 5); List<Product> listProducts = productService.getAll(); PageInfo<Product> productPageInfo = new PageInfo(listProducts); return productPageInfo; } /** * 獲取單個商品 使用ehcache * * @param id * @return */ @RequestMapping("getone/{id}") @ResponseBody public Object GetProduct(@PathVariable int id) { Product product = productService.selectByPrimaryKey(id); System.out.println("第一次查詢" + product.toString()); product = productService.selectByPrimaryKey(id); System.out.println("第二次查詢" + product.toString()); product = productService.selectByPrimaryKey(id); System.out.println("第三次查詢" + product.toString()); product = productService.selectByPrimaryKey(id); System.out.println("第四次查詢" + product.toString()); return product; } /** * 返回json測試 * * @return */ @RequestMapping("json") @ResponseBody private Object json() { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "測試姓名"); map.put("address", "深圳市南山區"); return map; } }
package ehcache.demo.service; import ehcache.demo.entity.Product; import java.util.List; public interface ProductService { public Product selectByPrimaryKey(int id); public List<Product> getAll() ; public Object deleteProduct(int id); public Object addProduct(Product product); public Object updateProduct(Product product); }
package ehcache.demo.service.Impl; import com.alibaba.fastjson.JSON; import ehcache.demo.entity.Product; import ehcache.demo.mapper.ProductMapper; import ehcache.demo.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductMapper productMapper; /* 注入springboot自動配置的redis */ @Autowired private RedisTemplate<Object, Object> redisTemplate; @Cacheable(value = "product", key = "#id") public Product selectByPrimaryKey(int id) { return productMapper.selectByPrimaryKey(id); } public List<Product> getAll() { // 創建redis序列化構造器,方便存儲可視化 RedisSerializer<?> redisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(redisSerializer); //序列化key // 查詢redis緩存 @SuppressWarnings("unchecked") List<Product> productList = (List<Product>) redisTemplate.opsForValue().get("allproducts"); /* 使用雙重驗證鎖解決高並發環境下的緩存穿透問題 */ if (productList == null) { // 第一重驗證 synchronized (this) { productList = (List<Product>) redisTemplate.opsForValue().get("allproducts"); if (productList == null) { // 第二重驗證 System.out.println("查詢數據庫............"); // 緩存為空,則查詢數據 entity需支持序列化 implements Serializable productList = productMapper.getAll(); // 數據庫查詢的數據保存至緩存 redisTemplate.opsForValue().set("allproducts", productList); } else { System.out.println("查詢緩存............"); } } } else { System.out.println("查詢緩存............"); } return productList; } public Object deleteProduct(int id) { return productMapper.deleteByPrimaryKey(id); } @Override public Object addProduct(Product product) { return productMapper.insert(product); } public Object updateProduct(Product product) { return productMapper.updateByPrimaryKey(product); } }
pom.xml文件配置
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>Ehcache</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.61</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.6.7</version> </dependency> <!--添加熱部署依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!--mybatis spring起步依賴--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <!-- tomcat對jsp支持開啟 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--jstl支持開啟 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet支持開啟 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <!--jstl支持開啟 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- 分頁插件開始 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.7</version> </dependency> <!-- 分頁插件結束 --> <!-- mysql支持開始 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <!-- mysql支持結束 --> <!-- 加載redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <!--添加防止生成后找不到XML、YML、properties文件--> <resources> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/*.*</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>