我正在尝试在 Web 应用程序中使用 proxool 连接池获取 jdbc 连接。下面的代码描述了相同的:
public static Connection getConnection(String key, boolean useConnectionPool, String poolName) {
Connection connection = null;
String alias = "DBCP" + poolName + "_" + key;
String driverClass = "com.mysql.jdbc.Driver";
checkAndLoadProps();
String driverUrl = "jdbc:mysql://" + props.getProperty(key + "_DBMS_URL") + "/" + props.getProperty(key + "_DEF_SCHEMA") + "?autoReconnect=true&useUnicode=true&characterEncoding=utf8&jdbcCompliantTruncation=false&rewriteBatchedStatement=true";
String connectionPoolUrl = "proxool." + alias + ":" + driverClass + ":" + driverUrl;
try {
if (useConnectionPool) {
info.remove("user");
String user = props.getProperty(key + "_CLIENT");
info.setProperty("user", user);
info.remove("password");
String password = props.getProperty(key + "_CLIENT_PASS");
info.setProperty("password", password);
String host = props.getProperty(key + "_DBMS_URL");
synchronized (poolName) {
connection = DriverManager.getConnection(connectionPoolUrl, info);
}
}
if (connection != null) {
return connection;
} else {
System.out.println("DB Connection Not Established");
}
} catch (Exception ex) {
System.out.println("DB Connection Not Established::" + ex.getMessage());
ex.printStackTrace();
}
return null;
}
一旦我启动服务器,就会发生超过 1 个线程尝试并行访问此代码并引发并发修改异常。
我知道可以通过为同步块提供类级锁定来修复它。但是会严重影响性能。
有什么更好的解决方案吗?