本文介绍了不使用JNDI管理数据库连接的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站,目前我获得了1000次网页浏览量。我预计它将来会每天大约30k。现在问题是我管理数据库连接。
目前我只是直接从java程序连接到DB。我知道这是世界上最糟糕的设计。但是暂时我写得那样。
我计划使用JNDI管理连接池。但问题是我的托管服务提供商不支持JNDI。

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 hosting provider is not supporting JNDI.

任何人都可以建议我如何在没有jndi的情况下管理数据库连接吗?

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

推荐答案

连接池本身并不要求JNDI获取连接。您还可以独立于JNDI设置和使用连接池。假设你想使用,这是一个更好的连接池,然后你可以在中找到原始无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.

以下是本教程的摘录:

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.

这篇关于不使用JNDI管理数据库连接的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 22:05