1. 程式人生 > >springboot~hazelcast快取中介軟體

springboot~hazelcast快取中介軟體

快取來了

在dotnet平臺有自己的快取框架,在java springboot裡當然了集成了很多,而且快取的中介軟體也可以進行多種選擇,向redis, hazelcast都是分散式的快取中介軟體,今天主要說一下後者的實現。

新增依賴包

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;
  }

}

新增倉儲

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

執行程式

可以在單元測試裡進行測試,呼叫多次,方法體只進入一次,這就是快取成功了。

@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();
  }
}