注: 本文首發於 博客 CodeSheep · 程序羊,歡迎光臨 小站!java
本文共 851字,閱讀大約須要 3分鐘 !mysql
本文內容腦圖以下: git
在現在高併發的互聯網應用中,緩存的地位舉足輕重,對提高程序性能幫助不小。而3.x開始的 Spring也引入了對 Cache的支持,那對於現在發展得如火如荼的 Spring Boot來講天然也是支持緩存特性的。固然 Spring Boot默認使用的是 SimpleCacheConfiguration,即便用ConcurrentMapCacheManager 來實現的緩存。但本文將講述如何將 Ehcache緩存應用到Spring Boot應用中。github
「Ehcache」 是一個基於Java實現的開源緩存管理庫,提供了用內存、磁盤文件存儲、以及分佈式存儲等多種靈活的管理方案。使用方式和原理都有點相似於 Spring事務管理,配合各項註解能夠很容易的上手。web
下文就上手來摸一摸它,結合對數據庫的操做,咱們讓 Ehcache做爲本地緩存來看一下效果!spring
好比我這裏準備了一張用戶表,包含幾條記錄:sql
咱們將經過模擬數據庫的存取操做來看看 Ehcache緩存加入後的效果。數據庫
pom.xml 中添加以下依賴:緩存
<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> <!--for mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--for Mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Spring boot Cache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!--for ehcache--> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> </dependencies>
建立Ehcache的配置文件 ehcache.xml並置於項目 classpath下:mybatis
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir"/> <!-- 設定緩存的默認數據過時策略 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> <cache name="user" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="10"/> </ehcache>
server.port=80 # Mysql 數據源配置 spring.datasource.url=jdbc:mysql://121.196.213.251:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=xxxxxx spring.datasource.driver-class-name=com.mysql.jdbc.Driver # mybatis 配置 mybatis.type-aliases-package=cn.codesheep.springbt_ehcache.entity mybatis.mapper-locations=classpath:mapper/*.xml mybatis.configuration.map-underscore-to-camel-case=true # ehcache 配置 spring.cache.ehcache.config=classpath:ehcache.xml
public class User { private Long userId; private String userName; private Integer userAge; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getUserAge() { return userAge; } public void setUserAge(Integer userAge) { this.userAge = userAge; } }
public interface UserMapper { List<User> getUsers(); int addUser(User user); List<User> getUsersByName( String userName ); }
@Service public class UserService { @Autowired private UserMapper userMapper; public List<User> getUsers() { return userMapper.getUsers(); } public int addUser( User user ) { return userMapper.addUser(user); } @Cacheable(value = "user", key = "#userName") public List<User> getUsersByName( String userName ) { List<User> users = userMapper.getUsersByName( userName ); System.out.println( "從數據庫讀取,而非讀取緩存!" ); return users; } }
看得很明白了,咱們在 getUsersByName
接口上添加了註解:@Cacheable
。這是 Ehcache的使用註解之一,除此以外經常使用的還有 @CachePut
和 @CacheEvit
,分別簡單介紹一下:
@Cacheable
:配置在 getUsersByName
方法上表示其返回值將被加入緩存。同時在查詢時,會先從緩存中獲取,若不存在纔再發起對數據庫的訪問@CachePut
:配置於方法上時,可以根據參數定義條件來進行緩存,其與 @Cacheable
不一樣的是使用 @CachePut
標註的方法在執行前不會去檢查緩存中是否存在以前執行過的結果,而是每次都會執行該方法,並將執行結果以鍵值對的形式存入指定的緩存中,因此主要用於數據新增和修改操做上@CacheEvict
:配置於方法上時,表示從緩存中移除相應數據。@RestController public class UserController { @Autowired private UserService userService; @Autowired CacheManager cacheManager; @GetMapping("/users") public List<User> getUsers() { return userService.getUsers(); } @GetMapping("/adduser") public int addSser() { User user = new User(); user.setUserId(4l); user.setUserName("趙四"); user.setUserAge(38); return userService.addUser(user); } @RequestMapping( value = "/getusersbyname", method = RequestMethod.POST) public List<User> geUsersByName( @RequestBody User user ) { System.out.println( "-------------------------------------------" ); System.out.println("call /getusersbyname"); System.out.println(cacheManager.toString()); List<User> users = userService.getUsersByName( user.getUserName() ); return users; } }
主要是在啓動類上經過 @EnableCaching註解來顯式地開啓 Ehcache緩存
@SpringBootApplication @MapperScan("cn.codesheep.springbt_ehcache") @EnableCaching public class SpringbtEhcacheApplication { public static void main(String[] args) { SpringApplication.run(SpringbtEhcacheApplication.class, args); } }
最終完工的整個工程的結構以下:
經過屢次向接口 localhost/getusersbyname
POST數據來觀察效果:
能夠看到緩存的啓用和失效時的效果(上文ehcache的配置文件中設置了緩存user的實效時間爲10s):
因爲能力有限,如有錯誤或者不當之處,還請你們批評指正,一塊兒學習交流!