我想在Helper类中为Oracle DB设置连接池。
public class DbConnection {
// Data source for the pooled connection
private static OracleDataSource dataSource;
// Host
private static final String dbHost = "bla";
// Port
private static final String dbPort = "1521";
// DBname
private static final String database = "orcl";
// DBuser
private static final String dbUser = "bla";
// DBpassword
private static final String dbPassword = "bla";
static {
OracleConnectionPoolDataSource opds;
try {
opds = new OracleConnectionPoolDataSource();
opds.setURL("jdbc:oracle:thin:@" + dbHost + ":" + dbPort + ":"
+ database);
opds.setUser(dbUser);
opds.setPassword(dbPassword);
dataSource = opds;
} catch (SQLException e1) {
System.err.println("Connection failed!");
}
try {
// Load driver
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found!");
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
这是有效的,但速度并不快,所以我觉得我错过了一些让游泳池工作的东西。有什么建议吗?
所以我的externel类只调用getConnection()方法......
Connection conn = DbConnection.getConnection();
...
conn.close();
答案 0 :(得分:2)
您不应直接使用ConnectionPoolDataSource
。它旨在供应用程序服务器中的连接池使用。它本身不提供连接池。另请参阅https://stackoverflow.com/a/12651163/466862
换句话说:您需要使用实际的连接池,如DBCP,c3p0或BoneCP,或UCP(通用连接池)。
答案 1 :(得分:1)
您需要使用OracleDataSource(而不是OracleConnectionPoolDataSource)并设置setConnectionCachingEnabled(true)。
private static OracleDataSource ods = null;
...
static {
System.out.println("OracleDataSource Initialization");
try {
ods = new OracleDataSource();
ods.setConnectionCachingEnabled(true);
ods.setConnectionCacheName("mycache");
ods.setURL("jdbc:oracle:thin:@//server.local:1521/prod");
ods.setUser("scott");
ods.setPassword("tiger");
Properties cacheProps = new Properties();
cacheProps.setProperty("MinLimit", "1");
cacheProps.setProperty("MaxLimit", "4");
cacheProps.setProperty("InitialLimit", "1");
cacheProps.setProperty("ConnectionWaitTimeout", "5");
cacheProps.setProperty("ValidateConnection", "true");
ods.setConnectionCacheProperties(cacheProps);
}
catch (SQLException e) {
e.printStackTrace();
}
}
...
public static Connection getConnection()
throws SQLException {
return ods.getConnection();
}
完整示例here。
答案 2 :(得分:1)
OutputStream os = urlConnection.getOutputStream();
os.write( message.getBytes());
os.close();
文档说明如下:
已过时。改为使用Oracle通用连接池。
您可以按照以下步骤下载Oracle Database UCP并创建oracle.jdbc.pool.OracleDataSource.setConnectionCachingEnabled
:
DataSource