緩存來了
在dotnet平臺有自己的緩存框架,在java springboot里當然了集成了很多,而且緩存的中間件也可以進行多種選擇,向 redis , hazelcast 都是分布式的緩存中間件,今天主要說一下后者的實現。
添加依賴包
1
2
3
4
5
6
7
|
dependencies { compile( "org.springframework.boot:spring-boot-starter-cache" ) compile( "com.hazelcast:hazelcast:3.7.4" ) compile( "com.hazelcast:hazelcast-spring:3.7.4" ) } bootrun { systemproperty "spring.profiles.active" , "hazelcast-cache" } |
config統一配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@configuration @profile ( "hazelcast-cache" ) //運行環境名稱 public class hazelcastcacheconfig { @bean public config hazelcastconfig() { config config = new config(); config.setinstancename( "hazelcast-cache" ); mapconfig alluserscache = new mapconfig(); alluserscache.settimetoliveseconds( 3600 ); alluserscache.setevictionpolicy(evictionpolicy.lfu); config.getmapconfigs().put( "alluserscache" , alluserscache); mapconfig usercache = new mapconfig(); usercache.settimetoliveseconds( 3600 ); //超時時間為1小時 usercache.setevictionpolicy(evictionpolicy.lfu); config.getmapconfigs().put( "usercache" , usercache); //usercache為緩存的cachename return config; } } |
添加倉儲
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public interface userrepository { list<userinfo> fetchallusers(); list<userinfo> fetchallusers(string name); } @repository @profile ( "hazelcast-cache" ) // 指定在這個hazelcast-cache環境下,userrepository的實例才是userinforepositoryhazelcast public class userinforepositoryhazelcast implements userrepository { @override @cacheable (cachenames = "usercache" , key = "#root.methodname" ) // 無參的方法,方法名作為key public list<userinfo> fetchallusers(){ list<userinfo> list = new arraylist<>(); list.add(userinfo.builder().phone( "135" ).username( "zzl1" ).createat(localdatetime.now()).build()); list.add(userinfo.builder().phone( "136" ).username( "zzl2" ).createat(localdatetime.now()).build()); return list; } @override @cacheable (cachenames = "usercache" , key = "{#name}" ) // 方法名和參數組合做為key public list<userinfo> fetchallusers(string name) { list<userinfo> list = new arraylist<>(); list.add(userinfo.builder().phone( "135" ).username( "zzl1" ).createat(localdatetime.now()).build()); list.add(userinfo.builder().phone( "136" ).username( "zzl2" ).createat(localdatetime.now()).build()); return list; } } |
配置profile
application.yml開啟這個緩存的環境
profiles.active: hazelcast-cache
運行程序
可以在單元測試里進行測試,調用多次,方法體只進入一次,這就是緩存成功了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@activeprofiles ( "hazelcast-cache" ) public class usercontrollertest extends basecontrollertest { @test public void fetchusers() { getok(); //test caching getok(); } private webtestclient.responsespec getok() { return http.get() .uri( "/users/all/zzl" ) .exchange() .expectstatus().isok(); } } |
總結
以上所述是小編給大家介紹的springboot hazelcast緩存中間件的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/lori/p/9518892.html