我正在做一个项目,我需要根据表建立不同的数据库连接。所有表格和连接详细信息都在config.properties file
. 所以假设我有两个表,config.properties
文件中有连接详细信息。然后每个线程将在database connections
任何时候产生两个run method
。
下面的方法将读取属性文件并ReadTableConnectionInfo object
为每个表创建一个。
private static void readPropertyFile() throws IOException {
prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));
tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));
for (String arg : tableNames) {
ReadTableConnectionInfo ci = new ReadTableConnectionInfo();
String url = prop.getProperty(arg + ".url");
String user = prop.getProperty(arg + ".user");
String password = prop.getProperty(arg + ".password");
String driver = prop.getProperty(arg + ".driver");
ci.setUrl(url);
ci.setUser(user);
ci.setPassword(password);
ci.setDriver(driver);
tableList.put(arg, ci);
}
}
下面的类将保存特定表的所有表连接信息。
public class ReadTableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
从下面的代码中,我尝试通过传入和来ReadTask class
使用多个线程执行tableList map
,每个线程将根据.constructor
run method
different database connections
tableLists size
ExecutorService service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < threads; i++) {
service.submit(new ReadTask(tableList));
}
public ReadTask(HashMap<String, ReadTableConnectionInfo> tableList) {
this.tableLists = tableList;
}
@Override
public void run() {
int j = 0;
dbConnection = new Connection[tableLists.size()];
statement = new Statement[tableLists.size()];
//loop around the map values and make the connection list
for (ReadTableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
statement[j] = dbConnection[j].createStatement();
j++;
}
}
我的问题是- 有没有更好的设计来解决类似的问题?就像每个线程应该创建不同的数据库连接并将其存储在一个列表中,以便我可以正确使用它们。