本次內容主要介紹基于ehcache 3.0來快速實現spring boot應用程序的數據緩存功能。在spring boot應用程序中,我們可以通過spring caching來快速搞定數據緩存。接下來我們將介紹如何在三步之內搞定spring boot緩存。
1. 創建一個spring boot工程并添加maven依賴
你所創建的spring boot應用程序的maven依賴文件至少應該是下面的樣子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
<?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> <parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version> 2.1 . 3 .release</version> <relativepath/> <!-- lookup parent from repository --> </parent> <groupid>com.ramostear</groupid> <artifactid>cache</artifactid> <version> 0.0 . 1 -snapshot</version> <name>cache</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-cache</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.ehcache</groupid> <artifactid>ehcache</artifactid> </dependency> <dependency> <groupid>javax.cache</groupid> <artifactid>cache-api</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> </dependency> </dependencies> <build> <plugins> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> </plugin> </plugins> </build> </project> |
依賴說明:
- spring-boot-starter-cache為spring boot應用程序提供緩存支持
- ehcache提供了ehcache的緩存實現
- cache-api 提供了基于jsr-107的緩存規范
2. 配置ehcache緩存
現在,需要告訴spring boot去哪里找緩存配置文件,這需要在spring boot配置文件中進行設置:
1
|
spring.cache.jcache.config=classpath:ehcache.xml |
然后使用@enablecaching注解開啟spring boot應用程序緩存功能,你可以在應用主類中進行操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.ramostear.cache; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.cache.annotation.enablecaching; @springbootapplication @enablecaching public class cacheapplication { public static void main(string[] args) { springapplication.run(cacheapplication. class , args); } } |
接下來,需要創建一個ehcache的配置文件,該文件放置在類路徑下,如resources目錄下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<config xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns= "http://www.ehcache.org/v3" xmlns:jsr107= "http://www.ehcache.org/v3/jsr107" xsi:schemalocation=" http: //www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd http: //www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd"> <service> <jsr107:defaults enable-statistics= "true" /> </service> <cache alias= "person" > <key-type>java.lang. long </key-type> <value-type>com.ramostear.cache.entity.person</value-type> <expiry> <ttl unit= "minutes" > 1 </ttl> </expiry> <listeners> <listener> < class >com.ramostear.cache.config.personcacheeventlogger</ class > <event-firing-mode>asynchronous</event-firing-mode> <event-ordering-mode>unordered</event-ordering-mode> <events-to-fire-on>created</events-to-fire-on> <events-to-fire-on>updated</events-to-fire-on> <events-to-fire-on>expired</events-to-fire-on> <events-to-fire-on>removed</events-to-fire-on> <events-to-fire-on>evicted</events-to-fire-on> </listener> </listeners> <resources> <heap unit= "entries" > 2000 </heap> <offheap unit= "mb" > 100 </offheap> </resources> </cache> </config> |
最后,還需要定義個緩存事件監聽器,用于記錄系統操作緩存數據的情況,最快的方法是實現cacheeventlistener接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package com.ramostear.cache.config; import org.ehcache.event.cacheevent; import org.ehcache.event.cacheeventlistener; import org.slf4j.logger; import org.slf4j.loggerfactory; /** * @author ramostear * @create-time 2019/4/7 0007-0:48 * @modify by : * @since: */ public class personcacheeventlogger implements cacheeventlistener<object,object>{ private static final logger logger = loggerfactory.getlogger(personcacheeventlogger. class ); @override public void onevent(cacheevent cacheevent) { logger.info( "person caching event {} {} {} {}" , cacheevent.gettype(), cacheevent.getkey(), cacheevent.getoldvalue(), cacheevent.getnewvalue()); } } |
3. 使用@cacheable注解對方法進行注釋
要讓spring boot能夠緩存我們的數據,還需要使用@cacheable注解對業務方法進行注釋,告訴spring boot該方法中產生的數據需要加入到緩存中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.ramostear.cache.service; import com.ramostear.cache.entity.person; import org.springframework.cache.annotation.cacheable; import org.springframework.stereotype.service; /** * @author ramostear * @create-time 2019/4/7 0007-0:51 * @modify by : * @since: */ @service (value = "personservice" ) public class personservice { @cacheable (cachenames = "person" ,key = "#id" ) public person getperson( long id){ return person; } } |
通過以上三個步驟,我們就完成了spring boot的緩存功能。接下來,我們將測試一下緩存的實際情況。
4. 緩存測試
為了測試我們的應用程序,創建一個簡單的restful端點,它將調用personservice返回一個person對象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package com.ramostear.cache.controller; import com.ramostear.cache.entity.person; import com.ramostear.cache.service.personservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.http.httpstatus; import org.springframework.http.responseentity; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; /** * @author ramostear * @create-time 2019/4/7 0007-0:54 * @modify by : * @since: */ @restcontroller @requestmapping ( "/persons" ) public class personcontroller { @autowired private personservice personservice; @getmapping ( "/{id}" ) public responseentity<person> person( @pathvariable (value = "id" ) long id){ return new responseentity<>(personservice.getperson(id), httpstatus.ok); } } |
person是一個簡單的pojo類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package com.ramostear.cache.entity; import lombok.allargsconstructor; import lombok.getter; import lombok.noargsconstructor; import lombok.setter; import java.io.serializable; /** * @author ramostear * @create-time 2019/4/7 0007-0:45 * @modify by : * @since: */ @getter @setter @allargsconstructor @noargsconstructor public class person implements serializable{ private long id; private string username; private string email; } |
以上準備工作都完成后,讓我們編譯并運行應用程序。項目成功啟動后,使用瀏覽器打開: http://localhost:8080/persons/1 ,你將在瀏覽器頁面中看到如下的信息:
{"id":1,"username":"ramostear","email":"[email protected]"}
此時在觀察控制臺輸出的日志信息:
2019-04-07 01:08:01.001 info 6704 --- [nio-8080-exec-1] o.s.web.servlet.dispatcherservlet : completed initialization in 5 ms
2019-04-07 01:08:01.054 info 6704 --- [e [_default_]-0] c.r.cache.config.personcacheeventlogger : person caching event created 1 null com.ramostear.cache.entity.person@ba8a729
由于我們是第一次請求api,沒有任何緩存數據。因此,ehcache創建了一條緩存數據,可以通過 created 看一了解到。
我們在ehcache.xml文件中將緩存過期時間設置成了1分鐘(1),因此在一分鐘之內我們刷新瀏覽器,不會看到有新的日志輸出,一分鐘之后,緩存過期,我們再次刷新瀏覽器,將看到如下的日志輸出:
2019-04-07 01:09:28.612 info 6704 --- [e [_default_]-1] c.r.cache.config.personcacheeventlogger : person caching event expired 1 com.ramostear.cache.entity.person@a9f3c57 null
2019-04-07 01:09:28.612 info 6704 --- [e [_default_]-1] c.r.cache.config.personcacheeventlogger : person caching event created 1 null com.ramostear.cache.entity.person@416900ce
第一條日志提示緩存已經過期,第二條日志提示ehcache重新創建了一條緩存數據。
結束語
在本次案例中,通過簡單的三個步驟,講解了基于ehcache的spring boot應用程序緩存實現。文章內容重在緩存實現的基本步驟與方法,簡化了具體的業務代碼,有興趣的朋友可以自行擴展,期間遇到問題也可以隨時與我聯系。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://juejin.im/post/5ca8e8516fb9a05e3b24c01b