我正在尝试覆盖 Google Guava 的 CacheLoader loadAll() 方法。我想做一个批量查找并检索 Employee 集合中的所有文档,这些文档没有像CachesExplained中所说的那样特别请求:
请注意,您可以编写一个 CacheLoader.loadAll 实现来加载未特别请求的键的值。例如,如果计算某个组中的任何键的值会为您提供组中所有键的值,则 loadAll 可能会同时加载该组的其余部分。
我搜索了互联网,发现唯一与我的问题远程相关的帖子是Google Guava 的 CacheLoader loadAll() method Implementation Issues。但是,我仍然无法从我的集合中批量检索所有文档。每当我运行我的代码时,从数据库中检索到的唯一值是通过列表专门传入的值。
假设我有一个 Mongo 集合名称员工,其中包含 3 个员工文档:
{"_id" : "123", "John Doe", "CEO"}
{"_id" : "456", "Jane Doe", "President"}
{"_id" : "789", "Jimmy Doe", "CFO"}
员工等级:
public class Employee extends MongoDbModel {
@Id
private final String employeeNumber;
private final String name;
private final String type;
public Employee(String employeeNumber, String name, String type){
this.employeeNumber = employeeNumber;
this.name = name;
this.type = type;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public static LoadingCache<String, Employee> employeeCacheMap;
static {
employeeCacheMap = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.weakKeys()
.maximumSize(10000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build(
new CacheLoader<String, Employee>() {
@Override
public Employee load(String key) throws ExecutionException{
return getOneFromDatabase(key);
}
@Override
public Map<String, Employee> loadAll(Iterable<? extends String> key){
return getAllEmployeesFromDatabase();
}
}
);
}
private static Employee getOneFromDatabase(String employeeNumber){
return MongoDbStore.createQuery(Employee.class).filter("_id", employeeNumber).first();
}
private static Map<String, Employee> getAllEmployeesFromDatabase(){
final List<Employee> list = MongoDbStore.createQuery(Employee.class).asList();
final Map<String, Employee> map = new HashMap<String,Employee>(list.size());
for(final Employee employee : list){
map.put(employee.getName(), employee);
}
return map;
}
public static LoadingCache<String, Employee> getLoadingCache(){
return employeeCacheMap;
}
}
每当我运行此方法时:
public void getAllEmployees(){
List<String> myList = new ArrayList<>();
myList.add("123");
myList.add("456");
Map<String, Employee> employeeMap = null;
try {
employeeMap = Employee.getLoadingCache().getAll(myList);
} catch (ExecutionException e) {
e.printStackTrace();
}
for(Employee employee : employeeMap.values()){
System.out.println(employee.getName());
}
}
它只打印出来:
"John Doe"
"Jane Doe"
而不是上面引用的CachesExplained中描述的所有三个名称。
我是否误解了上面的引用,并且 CacheLoader 只检索传递给 loadAll() 方法的值,而不是从集合中检索所有值?任何帮助都感激不尽