@johnbollinger была очень полезна. Я реорганизовал код, чтобы получить соединение с SQL Server на высоком уровне вместо того, чтобы получить соединение для каждого запроса. Я действительно думаю, что мне все еще нужно появиться в темах, чтобы повысить производительность, чтобы сделать ее управляемой.
Код: Выделить всё
/**
* Get SQL Server connection
* @return
*/
private Connection getSQLCon() {
final SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setServerName(config.getAusNatServer().getName());
dataSource.setPortNumber(Integer.parseInt(config.getAusNatServer().getPort()));
dataSource.setDatabaseName(config.getAusNatServer().getDatabase());
dataSource.setUser(config.getAusNatServer().getUserId());
dataSource.setPassword(config.getAusNatServer().getAuthentication());
dataSource.setSendStringParametersAsUnicode(false);
try {
Connection conn = dataSource.getConnection();
return conn;
} catch (Exception e) {
LOGGER.error("Unable to connect to aus_national :{}",e.getMessage());
}
return null;
}
Код: Выделить всё
/**
* For each row, get the record from aus_national and retrieve the CRs.
*/
Connection sqlConn = thisRun.getSQLCon();
if(sqlConn != null) {
for(CaseData currentCase : cases) {
thisRun.extractCR(currentCase,sqlConn);
}
}
< /code>
Метод "extractcr ()" - это то, что я хочу запустить в различных темах.
Мой первый выстрел в его отладках (где вещи искусственно медленные). Моя (неосведомленная) теория заключается в том, что попытка создать кучу соединений одновременно была тем, что взорвала ее.
[b] Я добавил новый класс [/b]
package gov.usdohud.chums;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.logging.log4j.core.Logger;
import gov.usdohud.dao.CaseData;
import gov.usdohud.helper.AUSInflator;
import gov.usdohud.model.ConfigData;
@SuppressWarnings("unused")
public class ProcessCase extends Thread {
private CaseData currentCase;
private Connection conn;
private Logger LOGGER;
private ConfigData config;
public ProcessCase(CaseData currentCase, Connection conn,Logger logger, ConfigData config) {
this.currentCase = currentCase;
this.conn = conn;
this.LOGGER = logger;
this.config = config;
}
/**
* Use case data from sfdw to get the CR(s) from aus_national.
* @param currentCase
*/
private void run(CaseData currentCase, Connection conn,Logger LOGGER, ConfigData config) {
String loanNumber = currentCase.getLoan_nbr();
String caseNumber = currentCase.getCase_nbr();
String scoreDate = currentCase.getScore_dt();
String aus = currentCase.getUndrwrtr_id();
String sqlString = "select file_data from aus_credit where loan_number = ? and score_dt = ? and aus = ?";
// pull CR(s)
try {
PreparedStatement stmt = conn.prepareStatement(sqlString);
stmt.setString(1, loanNumber);
stmt.setString(2, scoreDate.replaceAll("\\..*$", "").replace("-", "/"));
stmt.setString(3, aus);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
int sequence = rs.getRow();
writeCR(caseNumber, rs.getBinaryStream("file_data"),sequence,config,LOGGER);
}
} catch (SQLException e) {
LOGGER.error("Case {} was not retrieved. Loan number is {}, score date is {}, and aus is {}",caseNumber,loanNumber,scoreDate.replaceAll("\\..*$", "").replace("-", "/"),aus);
}
}
/**
* Write each CR to text file as caseNumber-[sequence number]
* @param caseNumber
* @param string
*/
private void writeCR(String caseNumber, InputStream cr, int seq, ConfigData config, Logger LOGGER) {
final String fn = config.getDataFolder() + "/" + caseNumber + "-" + String.valueOf(seq) + ".txt";
AUSInflator decode = new AUSInflator();
byte[] crBytes = null;
try {
crBytes = cr.readAllBytes();
} catch (IOException e) {
LOGGER.error("Unable to get CR data for case {}, sequence {} : {}", caseNumber, seq,e);
}
String thisCR = decode.unZipIt(crBytes).replaceAll("", "").replaceAll("", "");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fn))) {
writer.write(thisCR);
} catch (IOException e) {
LOGGER.error("Unable to create CR file for case {}, sequence {} : {}", caseNumber, seq,e);
}
}
}
Connection sqlConn = thisRun.getSQLCon();
if(sqlConn != null) {
for(CaseData currentCase : cases) {
ProcessCase storeCase = new ProcessCase(currentCase, sqlConn, (org.apache.logging.log4j.core.Logger) LOGGER, config);
Thread workerThread = new Thread(storeCase);
workerThread.start();
}
}
< /code>
Я не получаю ошибок, но я тоже не получаю результатов.
У меня есть точки разрыва в классе потока на первом операторе в конструкторе, и на первом операторе в методе запуска. Я думал, что называть "kykerthread.start ()" сбросит метод запуска в классе потока. Я также попробовал "korkerthread.run ()" и получил такое же поведение.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... ementation
Мобильная версия