无需 JNDI 即可管理数据库连接的最佳方法

发布于 2024-09-25 16:16:33 字数 183 浏览 3 评论 0原文

我有一个网站,目前我的页面浏览量为 1000。我预计未来每天会达到30k左右。现在我面临管理数据库连接的问题。 目前我只是直接从java程序连接到DB。我知道这是世界上最糟糕的设计。但我暂时是这样写的。 我计划使用 JNDI 管理连接池。但问题是我的托管提供商不支持 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坐在坟头思考人生 2024-10-02 16:16:33

连接池本身并不要求通过 JNDI 获取连接。您还可以独立于 JNDI 设置和使用连接池。假设您想使用 C3P0,这是更好的连接池之一,那么您可以在本教程中找到“原始”JNDI-less 设置详细信息。

以下是本教程的摘录:

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"); 

在应用程序启动期间创建一次数据源并将其存储在上下文中的某个位置。然后可以按如下方式获取和使用连接:

Connection connection = null;
// ...

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

是的,最后关闭仍然是强制性的,否则连接池将无法将连接放回池中以供将来重用,并且会耗尽连接。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文