2 回答

TA貢獻(xiàn)1775條經(jīng)驗 獲得超8個贊
您必須將三個CompletableFutures 的結(jié)果合并為一個EmployeeDTO. 這不是魔術(shù)般地完成的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();
這看起來有點(diǎn)傻。我們在每種方法中都使用一個構(gòu)建器,只是為了使用第四個構(gòu)建器組合它們的結(jié)果。

TA貢獻(xiàn)1842條經(jīng)驗 獲得超22個贊
讓您的員工服務(wù)函數(shù)將EmployeeDTO.builder()作為輸入,然后在 run() 函數(shù)中創(chuàng)建一個構(gòu)建器,并在所有 supplyAsync 調(diào)用中將該構(gòu)建器傳遞給服務(wù)。還要確保在調(diào)用 allOf() 之后調(diào)用 build() ,這保證了每個服務(wù)調(diào)用都完成了它的一部分。也不要內(nèi)置單獨(dú)的服務(wù)功能 -
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();
}
添加回答
舉報