springboot + ehcache快取
阿新 • • 發佈:2018-11-27
springboot + ehcache快取
1. 載入依賴包
<!-- caching --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
2.新增ehcache.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"> <diskStore path="java.io.tmpdir" /> <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <cache name="userCache" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="300" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"> <!-- 配置快取事件監聽器 replicateAsynchronously 操作是否非同步,預設值為true. replicatePuts 新增操作是否同步到叢集內的其他快取,預設為true. replicateUpdates 更新操作是否同步到叢集內的其他快取,預設為true. replicateUpdatesViaCopy 更新之後的物件是否複製到叢集中的其他快取(true); replicateRemovals 刪除操作是否同步到叢集內的其他快取,預設為true. --> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties=" replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=true, replicateRemovals=true " /> <!-- 初始化快取,以及自動設定 --> <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" /> </cache> </ehcache>
3.在application.properties設定快取,掃描ehcache.xml(這裡就和ehcacheManager類似,建立快取管理器)
#cache 多個用逗號分開
spring.cache.cache-names=userCache
spring.cache.jcache.config=classpath:ehcache.xml
4.同樣是在application.properties檔案中(為了便於檢視是否是通過了資料庫查詢,還是通過快取,我們需要在控制檯列印,是否呼叫了mapper中的sql語句),所以需要,開啟debug列印,並且掃描需要列印的mapper(和資料庫互動,有sql語句的包)
##預設情況下,spring boot從控制檯打印出來的日誌級別只有ERROR, WARN 還有INFO,如果你想要 列印debug級別的日誌,可以通過application.properites配置debug=true
debug=true
#
##配置logging.level.*來具體輸出哪些包的日誌級別
#logging.level.org.springframework.web=DEBUG
logging.level.com.lbl.mapper=DEBUG
5.mapper檔案,主要是@CacheConfig(cacheNames = “userCache”)將快取存入快取管理器
@CacheConfig等註解詳情 https://www.jb51.net/article/112849.htm 等都可百度
package com.lbl.mapper;
import com.lbl.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
@Mapper
@CacheConfig(cacheNames = "userCache")
public interface UserMapper {
//獲取使用者資訊
@Cacheable
@Select("select * from user where ID = 1")
User getUser();
@Select("select * from user")
List<User> findAll();
@Select("select count(1) from user")
Integer countItem();
}
6.controller 分頁功能在前一篇說到,這裡只用了getUer測試
package com.lbl.controller;
import com.lbl.entity.User;
import com.lbl.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private IUserService userService;
@GetMapping("/getUser")
public User getUser(){
User user = new User();
return userService.getUser(1);
}
@GetMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
/**
* 商品分頁功能(整合mybatis的分頁外掛pageHelper實現)
* @param currentPage :當前頁數
* @param pageSize :每頁顯示的總記錄數
* @return
*/
@RequestMapping("/findByPage")
@ResponseBody
public List<User> itemsPage(int currentPage,int pageSize){
return userService.findItemByPage(currentPage, pageSize);
}}
7.測試檔案test.java
package com.lbl.sbm;
import com.lbl.entity.User;
import com.lbl.service.IUserService;
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;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SbmApplicationTests {
@Autowired
private IUserService userService;
@Test
public void contextLoads() {
User user1 = userService.getUser(1);
System.out.println("第一次"+user1);
User user2 = userService.getUser(1);
System.out.println("第二次"+user2);
}
}
8.最後就是在app檔案中開啟快取就ok了 ,就可以看到 第一次查詢呼叫了sql語句,第二次查詢沒有
package com.lbl.sbm;
import com.github.pagehelper.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import java.util.Properties;
@SpringBootApplication
// 啟用快取註解
@EnableCaching
@EntityScan("com.lbl.entity")
@MapperScan("com.lbl.mapper")
@ComponentScan(basePackages={"com.lbl.controller","com.lbl.service"})
public class SbmApplication {
public static void main(String[] args) {
SpringApplication.run(SbmApplication.class, args);
}
//分頁
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
p.setProperty("dialect", "mysql");
p.setProperty("supportMethodsArguments", "false");
p.setProperty("pageSizeZero", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
效果如是:第一次呼叫了資料庫,第二次就是直接在快取中直接查詢,這樣可以提高效率
反之:沒有// 啟用快取註解
@EnableCaching
效果如是:兩次都是呼叫了查詢資料庫
9.差不多了,簡單總結就是,jar包->配置快取檔案->載入配置->設定類/方法新增某個快取->app開啟@EnableCaching就差不多了