緩存來了java
在dotnet平臺有本身的緩存框架,在java springboot裏固然了集成了不少,並且緩存的中間件也能夠進行多種選擇,向redis, hazelcast都是分佈式的緩存中間件,今天主要說一下後者的實現。redis
若是想學習Java工程化、高性能及分佈式、深刻淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友能夠加個人Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給你們。spring
添加依賴包數組
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統一配置緩存
@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; } }
添加倉儲springboot
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; } }
配置profileapp
若是想學習Java工程化、高性能及分佈式、深刻淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友能夠加個人Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給你們。框架
application.yml開啓這個緩存的環境分佈式
profiles.active: hazelcast-cache
運行程序ide
能夠在單元測試裏進行測試,調用屢次,方法體只進入一次,這就是緩存成功了。
@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(); } }
若是想學習Java工程化、高性能及分佈式、深刻淺出。微服務、Spring,MyBatis,Netty源碼分析的朋友能夠加個人Java高級交流:854630135,羣裏有阿里大牛直播講解技術,以及Java大型互聯網技術的視頻免費分享給你們。