缓存来了
在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 { ListfetchAllUsers(); List 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 fetchAllUsers(){ List 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 fetchAllUsers(String name) { List 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(); } }
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔