我有套接字連接,它將通過databaseQueue.add(message);
將數據發送到隊列中。接下來是DatabaseProcessor
類,它是在啓動單線程數據庫連接的起始線程中啓動的。連接將繼續通過databaseQueue.take();
和進程接收消息。關於這部分的好處就是隻有一個數據庫連接。突然出現數據激增時出現問題。所以另一種方法是對於每個收到的數據我會打開和關閉方法。那麼根據你的重負載體驗,這是去這裏最好的方法嗎?隊列方法或個人數據庫連接?
我的一些代碼片段。
class ConnectionHandler implements Runnable {
ConnectionHandler(Socket receivedSocketConn1) {
this.receivedSocketConn1=receivedSocketConn1;
}
// gets data from an inbound connection and queues it for databse update
public void run() {
databaseQueue.add(message); // put to db queue
}
}
class DatabaseProcessor implements Runnable {
public void run()
{
// open database connection
createConnection();
while (true)
{
message = databaseQueue.take(); // keep taking message from the queue add by connectionhandler and here I will have a number of queries to run in terms of select,insert and updates.
}
}
void createConnection()
{
System.out.println("Crerate Connection");
connCreated = new Date();
try
{
dbconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?"+"user=user1&password=*******");
dbconn.setAutoCommit(false);
}
catch(Throwable ex)
{
ex.printStackTrace(System.out);
}
}
}
public void main()
{
new Thread(new DatabaseProcessor()).start(); //calls the DatabaseProcessor
//initiate the socket
}
不,我不爲每條新消息創建新線程我通過主創建一個線程,永遠保持接收消息並傳遞到另一個單獨的線程處理數據庫的東西。那麼我是否仍然需要同步 – user837306 2012-02-13 03:34:08