简体   繁体   English

在Servlet之间共享连接池

[英]Share connection pool among servlets

I'd like to share a database connection among servlets. 我想在servlet之间共享数据库连接。

I created the connection pool and I obtain the dataSource object like this 我创建了连接池,并获得了像这样的dataSource对象

Context envContext  = (Context)context.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/limedb");

Now, I'd like to share this dataSource object among servlet so that each servlet can just do 现在,我想在servlet之间共享此dataSource对象,以便每个servlet都可以

connection = dataSource.getConnection();

to get its own connection. 获得自己的连接。

What is the best method to achieve this? 达到此目的的最佳方法是什么? I'd like to create the pool at the application startup and store it somewhere... 我想在应用程序启动时创建池并将其存储在某处...

There are actually a few ways you can do this. 实际上,您可以通过几种方法来执行此操作。

  1. You can use a dependency injection framework to manage those connections for you. 您可以使用依赖项注入框架为您管理那些连接。 Behind the scenes it will use an object pool. 在幕后它将使用对象池。
  2. You can create a singleton object that manages an object pool containing datasources for you. 您可以创建一个单例对象,该对象可以为您管理包含数据源的对象池。
  3. You can write a singleton containing the code that returns the connection for you, so you don't have to know you are using a datasource. 您可以编写一个单例,其中包含为您返回连接的代码,因此您不必知道自己在使用数据源。

It all depends on the use case, how familiar you are with java, the overall design of your application, etc. 这完全取决于用例,您对Java的熟悉程度,应用程序的整体设计等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM