[英]How to multithread stored procedure calls in java from an array list?
我目前有一個Java程序,該程序運行一個存儲過程,一次從數組列表中循環調用一條記錄,直到遍歷所有記錄為止。 當前從存儲過程調用返回的每條記錄大約需要8秒鍾。 完成調用后,它將從SP中獲取XML消息,並繼續在代碼中將該消息寫入隊列,然后更新數據庫中的字段以將記錄標記為已處理。
我想做的是讓x個線程一次命中/調用存儲過程,以加快整個數組列表的處理時間,並像現在一樣繼續執行其他步驟。 數組列表的范圍從幾百條記錄到4000條以上。
有沒有辦法在調用后仍然通過相同的過程,但是添加多線程來一次多次擊中SP,而不會互相影響呢? 我只編碼了很短的時間,所以請多多包涵,謝謝!
public void callStoredProcedure(){
Connection conn = null;
DSConnection dsc = new DSConnection();
CallableStatement callableStatement = null;
/*
* stored procedure LWN_XML_PURCHASEORDER
*
* in_company IN NUMBER,
in_PO_NUMBER IN VARCHAR2,
in_po_release IN NUMBER,
in_po_code IN VARCHAR2,
in_object_TYPE IN VARCHAR2,
RET_CODE OUT NUMBER,
RET_MSG OUT CLOB)
*/
ArrayList<YmpohdroutDbo> PurchOrderList = new ArrayList<YmpohdroutDbo>(getInsertUpdatePurchOrders().values());
try {
//conn = dsc.getConnection();
ProcedureResult res;
for(int i=0;i<PurchOrderList.size();i++) {
conn = dsc.getConnection();
// calling SP
callableStatement = conn.prepareCall("{ call "+PurchaseOrder.dbProperties.getProperty("Schema") +".LWN_XML_PURCHASEORDER(?,?,?,?,?,?,?)}");
// register input fields of SP
callableStatement.setInt(1, PurchOrderList.get(i).getCompany());
callableStatement.setString(2, PurchOrderList.get(i).getPO_Number());
callableStatement.setInt(3, PurchOrderList.get(i).getPO_Release());
callableStatement.setString(4, PurchOrderList.get(i).getPO_Code());
callableStatement.setString(5, (PurchaseOrder.projProperties.getProperty(Constants.SEC_KEY_COMMENT_TYPE)));
// register output fields of stored procedure
callableStatement.registerOutParameter(6, java.sql.Types.INTEGER);
callableStatement.registerOutParameter(7, java.sql.Types.CLOB);
// execute LWN_XML_PURCHASEORDER SP
callableStatement.execute();
res = new ProcedureResult();
res.setCode(callableStatement.getInt(6));
res.setMessage(callableStatement.getClob(7));
// send response from SP to MQ
PurchaseOrder.writeClobMQMessage(res.getMessage());
// mark record as processed
markRecordAsProcessed(PurchOrderList.get(i), conn);
DSConnection.close(conn, null, callableStatement, null);
}
} catch (Exception e) {
logger.error(e);
System.exit(1);
} finally {
if (callableStatement != null) {
try {
callableStatement.close();
} catch (SQLException e) {
logger.error(e);
}
}
if (conn != null) {
DSConnection.close(conn, null, callableStatement, null);
}
}
}
您可以簡單地啟動多個線程,每個線程執行相同的方法callStoredProcedure。 唯一的更改是將PurchOrderList從callStoredProcedure中移出,以使其對所有線程都通用,並將其轉換為隊列而不是ArrayList。
UPDT是生產者-消費者模式的一種特殊情況,其中單個生產者填充隊列,幾個消費者從隊列中獲取項目(記錄)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.