Multiple database queries in parallel, for a single client request

时光总嘲笑我的痴心妄想 提交于 2019-12-10 14:48:10

问题


To complete certain requests from the user, in my application, I am issuing multiple DB queries from a single method, but they are currently being executed sequentially & thus the application is blocked until the time it has received the response/data for the previous query, then proceeding to next query. This is not something I like much. I would like to issue parallel queries.

Also after issuing queries I would like to do some other work, (instead of being blocked till previous queries response) & on getting the response for each query I would like to execute a code block specific to each query's data. What is the way to do this ?

Edit:My DB API does provide connection pooling.


I'm just a little bit familiar with Java multithreading.

Using:-
------
Java 1.6
Cassandra 1.1 Database with Hector

回答1:


You should understand before you start doing this

  1. To benefit from concurrency, you need to have multiple db connections. THe best way to solve this is to create a db pool.

  2. You need to create a runnable / callable class for executing a db Statement. You will need to put together some messaging system to alert listeners to when your query has completed

  3. Understand that when you are sending multiple requests at the same time, all bets are off as to which will complete first, and that there may be conflicts between statements that destabilize your app.




回答2:


I have the similar task/issue. For complete build result I need to send few requests for few different service (few on REST, few on Thrift), for decrease latency I need to sent it in parallel. My idea is using java.util.concurrent.Future, make simple aggregation manager , which create many requests together and will be wait last retrieved response and return all needed data. In more advanced solution this manager can make/combine final result during other queries, but this solution can be not thread safe.




回答3:


Here's a very trivial/limited approach:

final Connection conn = ...;
final Object[] result = new Object[1];
Thread t1 = new Thread(new Runnable() {
    public void run() {
        Object results = conn.executeQuery();
        result[0] = results;
    }
});
t1.setName("DBQueryWorker");
t1.start();
// do other work
while (t1.isAlive()) {
   // wait on thread one
}

This is a simple approach, but many others are possible (eg, thread pooling via Java Concurrency task executors, Spring task executors, etc).



来源:https://stackoverflow.com/questions/9932653/multiple-database-queries-in-parallel-for-a-single-client-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!