springboot~hazelcast緩存中間件

緩存來了

在dotnet平臺有自己的緩存框架,在java springboot裏當然了集成了很多,而且緩存的中間件也可以進行多種選擇,向redis, hazelcast都是分佈式的緩存中間件,今天主要說一下後者的實現。

如果想學習Java工程化、高性能及分佈式、深入淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友可以加我的Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給大家。

添加依賴包

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統一配置

@Configurationbr/>@Profile("hazelcast-cache")//運行環境名稱
public class HazelcastCacheConfig {
br/>@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;
}
}
添加倉儲

public interface UserRepository {
List<UserInfo> fetchAllUsers();
List<UserInfo> fetchAllUsers(String name);br/>}
@Repository
@Profile("hazelcast-cache")// 指定在這個hazelcast-cache環境下,UserRepository的實例纔是UserInfoRepositoryHazelcast
public class UserInfoRepositoryHazelcast implements UserRepository {
br/>@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;
br/>}
@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

如果想學習Java工程化、高性能及分佈式、深入淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友可以加我的Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給大家。

application.yml開啓這個緩存的環境

profiles.active: hazelcast-cache
運行程序

可以在單元測試裏進行測試,調用多次,方法體只進入一次,這就是緩存成功了。

@ActiveProfiles("hazelcast-cache")
public class UserControllerTest extends BaseControllerTest {br/>@Test
public void fetchUsers() {
getOk();
//test caching
getOk();
}
private WebTestClient.ResponseSpec getOk() {
return http.get()
.uri("/users/all/zzl")
.exchange()
.expectStatus().isOk();
}
}
如果想學習Java工程化、高性能及分佈式、深入淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友可以加我的Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給大家。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章