2 回答

TA貢獻1775條經(jīng)驗 獲得超8個贊
您必須將三個CompletableFutures 的結果合并為一個EmployeeDTO. 這不是魔術般地完成的allOf。
嘗試這樣的事情(未經(jīng)測試):
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條經(jīng)驗 獲得超21個贊
讓您的員工服務函數(shù)將EmployeeDTO.builder()作為輸入,然后在 run() 函數(shù)中創(chuàng)建一個構建器,并在所有 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();
}
添加回答
舉報