当前位置: 移动技术网 > IT编程>开发语言>Java > springboot hazelcast缓存中间件的实例代码

springboot hazelcast缓存中间件的实例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

缓存来了

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

总结

以上所述是小编给大家介绍的springboot hazelcast缓存中间件的实例代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网