Answer the question
In order to leave comments, you need to log in
Is it correct to use CompletableFuture and JdbcTemplate in this way?
Hello. There is a task: to make one call to one database and another call to another database. Take action on the results.
My current implementation is as follows:
Dao1 makes a select query1.
Dao2 makes select query2.
We do processing of results of two requests.
It would be desirable request1 and request2 to do simultaneously. Implemented like this:
@Async
public CompletableFuture<Response1> query1(){
return CompletableFuture.completedFuture(jdbcTemplate1.query(sql, , ))
}
@Async
public CompletableFuture<Response2> query2(){
return CompletableFuture.completedFuture(jdbcTemplate2.query(sql, , ))
}
CompletableFuture<Response1> response1Future = query1();
CompletableFuture<Response2> response2Future = query2();
CompletableFuture.allOf(response1Future, response2Future).join();
//
Answer the question
In order to leave comments, you need to log in
public CompletionStage<DBResponse> query1(){
return queryAsync(jdbc, sql, param1, param2, ... paramN);
}
public CompletionStage<DBResponse> query2(){
return queryAsync(jdbc, sql, param2, param3, ... paramN);
}
public CompletionStage<DBResponse> queryAsync(JDBC jdbc, sql, Objects ... params){
return CompletableFuture.supplyAsync(() -> {
return jdbc.query(sql, params);
}).thenApplyAsync(DBResponse::of);
}
// далее в коде
void result(){
CompletableFuture.allOf(query1(), query2())
.thenAcceptAsync( ... );
}
public static interface DBResponse {
default DBResponse of(Response resp){
...;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question