implementation "com.github.ben-manes.caffeine:caffeine:2.8.6"
起初是为了存list,人员信息每次查询时候,都会传一组不同的list给我,我为了不每次都调用rpc接口,就想到用一个map<Long,Employee> 但是又要自行去过滤哪些不是map中已经存在的,而且不止我这要用到这个,所以我还得写个自定义注解@Around,就感觉有点麻烦
3.1先上代码再bb
public static final Cache<EmployeeId, com.ai.ep.domain.employee.Employee> employeeIdCache = Caffeine.newBuilder()
//存活时间十分钟
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(200)
.build();
public List<com.ai.ep.domain.employee.Employee> getHiredEmployeesByPersonIds(List<EmployeeId> personIds) {
Map<EmployeeId, com.ai.ep.domain.employee.Employee> all = employeeIdCache.getAll(personIds, employeeIds -> {
List<Employee> hiredEmployeesByPersonIds = employeeQuerySv.getHiredEmployeesByPersonIds(personIds.stream().map(EmployeeId::getId).collect(Collectors.toList()));
return hiredEmployeesByPersonIds.stream().map(converter::toEntity).collect(Collectors.toMap(com.ai.ep.domain.employee.Employee::getEmployeeId, employee -> employee));
});
//需要返回的员工List
return new ArrayList<>(all.values());
}
3.2getAll是先拿入参的list查询缓存,要是入参的list刚好在缓存中都存在,那么直接返回。
如果部分存在,他就把不存在的那部分过滤出来,去执行逗号后边那个方法,再把方法的执行结果添加到”咖啡因“缓存中,最后返回数据
4.单个缓存get
get和getAll思想类似,也是缓存中没有的话就去执行都好后边的查询方法,并把结果加载到缓存中
4.1上代码
public static final Cache<Long, Employee> personIdCache = Caffeine.newBuilder()
//存活时间十分钟
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(200)
.build();
public com.ai.ep.domain.employee.Employee find(EmployeeId employeeId) {
if (null == employeeId) {
return null;
}
return personIdCache.get(employeeId.getId(), id -> {
//调用rpc接口
Employee employee = employeeQuerySv.getHiredEmployeeByPersonId(id);
//实体转换
return converter.toEntity(employee);
});
}