[英]How to improve the performance of a query execution with bigger resultset in spring
[英]How to improve performance of JDBC query execution?
我正在Discord上運行一個機器人,該機器人接收到許多對MySQL數據庫的請求,最近MySQL已開始阻止線程,從而導致程序嚴重延遲。
轉儲線程后,我發現有問題的行駐留在JDBC的PreparedStatement代碼內,但是我真的不確定是什么引起了此問題。
下面的代碼塊是發生錯誤的位置:
public List<HashMap<String, Object>> find(String haystack, Object... needles){
PreparedStatement prep = null;
List<HashMap<String, Object>> results = new ArrayList<>();
ResultSet rs = null;
try{
prep = connection.prepareStatement(haystack);
for(int i = 0; i < needles.length; i++){
prep.setObject(i+1, needles[i]);
}
rs = prep.executeQuery();
while(rs.next()){
HashMap<String, Object> result = new HashMap<>();
for(int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++){
result.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
}
results.add(result);
}
}catch(SQLException e){
System.out.println("MySQL > Unable to execute query: " + e.getMessage());
}finally{
try{
if(rs!=null)rs.close();
if(prep!=null)prep.close();
}catch(SQLException e){
System.out.println("(find) Error closing: " + e.getMessage());
}
}
return results;
}
與rs = prep.executeQuery();
是有問題的代碼行。
有什么方法可以阻止MySQL阻止線程?
我看到您在整個應用程序中僅使用一個連接。 如果您有大量需要處理的請求,可以使用以下方法來創建連接池:
您可以在應用程序端創建連接池。 您可以使用apache連接池。
您可以在服務器端創建連接池。 讀這個。
最好使用hibernate ,那里有一個名為hibernate.connection.pool_size
的屬性。
如果你正在使用JDBC准備語句,然后使用批量處理 ,並避免使用Statement
(我看到你在做),因為在提到的原因這篇文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.