構築されました:
私は理解しようとしているCompletableFuture
とどのように私は、いくつかのエンドポイントから取得した情報を持つオブジェクトを構築し、それを利用することができます。私はいくつかの例に遭遇しましたが、どれも非常に私の問題に合わせていません。例えば、この1は私が構築したオブジェクトを返すために並列に複数のメソッドを実行したい文字列のリストを取得するには、並列に同じ方法を実行しています。
私は従業員のためのシンプルなDTOを作成しました:
@Builder
@Data
@AllArgsConstructor
public class EmployeeDTO {
private String name;
private String accountNumber;
private int salary;
}
私はかなりの待ち時間とDTOの値を設定するには、3つの別々のAPIへの模倣呼び出しにサービスを作成しました:
public class EmployeeService {
public EmployeeDTO setName() {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return EmployeeDTO.builder().name("John Doe").build();
}
public EmployeeDTO setAccountNumber() {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return EmployeeDTO.builder().accountNumber("1235").build();
}
public EmployeeDTO setSalary() {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return EmployeeDTO.builder().salary(100000).build();
}
}
私がすることができますsupplyAsync
方法の3つのすべてをしてから実行しますallOf
が、それは何もしません。
private void run() {
EmployeeService employeeService = new EmployeeService();
CompletableFuture<EmployeeDTO> employeeCfWithName = CompletableFuture
.supplyAsync(employeeService::setName);
CompletableFuture<EmployeeDTO> employeeCfWithAccountNumber = CompletableFuture
.supplyAsync(employeeService::setAccountNumber);
CompletableFuture<EmployeeDTO> employeeCfWithSalary = CompletableFuture
.supplyAsync(employeeService::setSalary);
CompletableFuture allCompletableFutures = CompletableFuture.allOf(employeeCfWithName, employeeCfWithAccountNumber, employeeCfWithSalary);
}
どのように私は1 EmployeeDTOに結果を結合することができますか?
user11044402:
次の3つの結果を結合する必要がありますCompletableFuture
、単一に秒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();
これは愚かな少し見えます。私達はちょうど第四ビルダーを使用して、その結果を結合するためにあらゆる方法でBuilderを使用します。