how to do connection pooling in java?

∥☆過路亽.° 提交于 2019-11-28 09:29:51
paulsm4

You can get a third-party library, or you can use the connection pooling your Java EE container (for example, JBoss or WebSphere) provides for you.

To do this, you configure and use a JNDI datasource.

Here are details for Tomcat:

A connection pool operates by performing the work of creating connections ahead of time. In the case of a JDBC connection pool, a pool of Connection objects is created at the time the application server starts. The client can access the connection object in connection pool and return the object to pool once the db work is completed.

Context.xml

   <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" 
maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" 
driverClassName="com.mysql.jdbc.Driver"               
url="jdbc:mysql://localhost:3306/cdcol"/>

//This should be added in the servers context,xml file. For example if you are using apache server then the context.xml will be found in C:\apache-tomcat-6.0.26\conf\Context.xml

web.xml

  <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

//This should be added in the web.xml of the local project. (Not in server's web.xml).

Context ctx=new InitialContext();
          Context envContext = (Context)ctx.lookup("java:comp/env");
          DataSource ds=(DataSource)envContext.lookup("jdbc/TestDB");//TestDB is the Database Name
          con=ds.getConnection();
          stmt = con.createStatement();

Connection pooling is the feature available in all major web and application servers. You can find the simple example on configuring with Tomcat. Tomcat Connection Pooling

But if you would like to write your own connection pooling then there are libraries available to write. Apache DBCP

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!