2 回答
TA贡献1775条经验 获得超8个赞
您必须将三个CompletableFutures 的结果合并为一个EmployeeDTO. 这不是魔术般地完成的allOf。
尝试这样的事情(未经测试):
CompletableFuture allCompletableFutures = CompletableFuture.allOf(
employeeCfWithName, employeeCfWithAccountNumber, employeeCfWithSalary);
// Wait for all three to complete.
allCompletableFutures.get();
// Now join all three and combine the results.
EmployeeDTO finalResult = EmployeeDTO.builder()
.name(new employeeCfWithName.join())
.accountNumber(new employeeCfWithAccountNumber.join())
.salary(new employeeCfWithSalary.join())
.build();
这看起来有点傻。我们在每种方法中都使用一个构建器,只是为了使用第四个构建器组合它们的结果。
TA贡献1842条经验 获得超21个赞
让您的员工服务函数将EmployeeDTO.builder()作为输入,然后在 run() 函数中创建一个构建器,并在所有 supplyAsync 调用中将该构建器传递给服务。还要确保在调用 allOf() 之后调用 build() ,这保证了每个服务调用都完成了它的一部分。也不要内置单独的服务功能 -
public class EmployeeService {
public EmployeeDTO setName(EmployeeDTO.EmployeeDTOBuilder builder) {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return builder.name("John Doe");
}
public EmployeeDTO setAccountNumber(EmployeeDTO.EmployeeDTOBuilder builder) {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return builder.accountNumber("1235");
}
public EmployeeDTO setSalary(EmployeeDTO.EmployeeDTOBuilder builder) {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return builder.salary(100000);
}
}
private void run() {
EmployeeService employeeService = new EmployeeService();
EmployeeDTO.EmployeeDTOBuilder builder = EmployeeDTO.builder();
CompletableFuture<EmployeeDTO> employeeCfWithName = CompletableFuture
.supplyAsync(()-> emoplyeeService.setName(builder));
CompletableFuture<EmployeeDTO> employeeCfWithAccountNumber = CompletableFuture
.supplyAsync(()-> emoplyeeService.setAccount(builder));
CompletableFuture<EmployeeDTO> employeeCfWithSalary = CompletableFuture
.supplyAsync(()-> emoplyeeService.setSalary(builder));
CompletableFuture allCompletableFutures = CompletableFuture.allOf(employeeCfWithName, employeeCfWithAccountNumber, employeeCfWithSalary);
builder.build();
}
添加回答
举报