开发者

Best way to manage DB connections without JNDI

开发者 https://www.devze.com 2023-01-18 08:54 出处:网络
I have a website, in which currently I am getting 1000 page views. I am expecting it will go around 30k per day in future. Now the problem for me to manage the DB connections.

I have a website, in which currently I am getting 1000 page views. I am expecting it will go around 30k per day in future. Now the problem for me to manage the DB connections. At present I am just connecting to DB directly from java program. I know it is worst design in the world. But for time being I have written like that. I have plan to manage connection pooling using JNDI. But the problem is my hosti开发者_C百科ng provider is not supporting JNDI.

Can anyone suggest me how to manage DB connections without jndi?


Connection pooling does not per se require the connections to be obtained by JNDI. You can also just setup and use a connection pool independently from JNDI. Let's assume that you'd like to use C3P0, which is one of the better connection pools, then you can find "raw" JNDI-less setup details in this tutorial.

Here's an extract of the tutorial:

ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password"); 

Create the datasource once during application's startup and store it somewhere in the context. The connection can then be acquired and used as follows:

Connection connection = null;
// ...

try {
    connection = cpds.getConnection();
    // ...
} finally {
    // ...
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

Yes, closing in finally is still mandatory, else the connection pool won't be able to take the connection back in pool for future reuse and it'll run out of connections.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号