简体   繁体   中英

Share connection pool among servlets

I'd like to share a database connection among servlets.

I created the connection pool and I obtain the dataSource object like this

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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