`
leonzhx
  • 浏览: 798615 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Simple Solution for Complex Java Web Applications: Connection Pools and JDBC

    博客分类:
  • Java
阅读更多

Practically every request from a user's JSP/servlet creates a new database connection, which takes time and exhausts system resources. Using a limited number of database connections substantially improves Web server productivity and eases the load on your database. To the extent that servlets enable you to store information between user requests, distributed programming solutions, such as connection pools, can help generate Web content dynamically, quickly loading data from your database to your Web site.

A connection pool helps you manage and control the database connections from JSP/servlets, where you can store information between client requests. This article discusses the advantages of using a connection pool in your Java distributed systems programming. It requires a working knowledge of Java Web programming, databases, and JDBC, as well as an environment where you can access these technologies.

 

What Exactly Is a Connection Pool?
To understand connection pools, first think of servlets. Servlets are easy; they're just ordinary Java classes. A servlet request loads a Java class into the JVM and creates an instance of this class. Further, this one class instance processes all client requests in a separate thread. Between breaks, the instance remains in resident condition and is not removed. This way, it keeps all available information as instance objects, which is exactly what the connection pool is.

 

Connection Pool Implementation
In the implementation in this article, a connection pool is a class with a number of JDBC Connection objects and access methods. You could also think of it as a container with a simple interface for controlling and managing database connections. To execute a SQL request, get data from the database, or change the data, open a database connection and get an object of Connection type. You will process all subsequent operations with this object. You can specify the size of your connection pool according to your available resources.

 

One class, SimpleConnectionPool, realizes a connection pool. It's comprised of a limited set of methods for database connection. In each case, functionality and class realization will vary depending on the existing task. This implementation acts as a basic skeleton for a connections storehouse.

The connection pool will do the following:

  • Enable a load-specific database driver for each database;
  • Get the reference to the SimpleConnectionPool object, which represents a connection pool exactly;
  • Get an available connection (of Connection type) from your storehouse;
  • Put a connection back into the storehouse;
  • Free all resources and closes all opened connections in your storehouse

Different implementations of a JDBC connection pool exist in different utility packages and frameworks (for example, the Jakarta Struts framework has org.apache.struts.util.GenericDataSource).

The SimpleConnectionPool class represents a uniform connections storehouse to a previously specified database. You need at least three arguments to access a database: the URL ID of the database, a user login, and a password. The URL ID consists of a protocol ID, a driver ID, and a database ID. The protocol ID is always jdbc, the driver ID could be odbc, oracle, mysql, etc., and the database ID depends only on the implementation of the database driver. For example, the URL ID "jdbc:odbc:test" can be used for database access via a JDBC-ODBC bridge, and the URL ID "jdbc:mysql:localhost/test" can be used to access a MySQL test database on localhost (some MySQL driver implementations require you to specify a user access login/password in the URL ID).

 

Initialize your storehouse and all the additional arguments in the constructor of the SimpleConnectionPool class:

 

 

 

 

The static method getInstance() creates a single instance of the SimpleConnectionPool class and returns a reference to it. Here, the Singleton design pattern allows you to create only one class instance and then return a reference to any number of requested objects:

 


...
static synchronized public SimpleConnectionPool getInstance(String URI, 
							String dbuser, 
							String dbpass, 
							String drivername, 
							int maxconn) {
	if (this.ref == null) {
		this.ref = new SimpleConnectionPool(URI, dbuser, dbpass, 
		drivername, maxconn);
	}
	this.clients++;
	return this.ref;
}
...

 

 

 

To get a database connection as a Connection object, use the getConnection() method:

 


...
public synchronized Connection getConnection() {
	Connection rescon = null;
	if (!this.freeConnections.isEmpty()) {
		rescon = (Connection)this.freeConnections.get(this.freeConnections.size()-1);
		this.freeConnections.remove(rescon);
		try {
			if (rescon.isClosed()) {
				System.out.println("Removed closed 
				connection!");
				// Try again recursively
				rescon = getConnection();
			}
		} catch (SQLException e) {
			System.out.println("Removed closed connection!");
			// Try again recursively
			rescon = getConnection();
		} catch (Exception e) {
			System.out.println("Removed closed connection!");
			// Try again recursively
			rescon = getConnection();
		}
	} else {
		rescon = createConnection();
	}
	return rescon;
}
...

 

 

As you can see, the getConnection() method checks the ArrayList container to see whether it has any elements from which it can get an available connection and return it to the client. If it doesn't find any elements (no connections found), it creates a new connection to return to the client. So, getConnection() checks for available connections. In case you get an exception (for any reason), you repeat the process recursively--until you find a connection, you don't create a new connection. When ArrayList doesn't have any connections, you create a new connection using the createConnection() method:

 


...
private Connection createConnection() {
	Connection rescon = null;
	try {
		if (this.dbuser == null) {
			rescon = DriverManager.getConnection(this.URI);
		} else {
			rescon = DriverManager.getConnection(this.URI, 
			this.dbuser, this.dbpass);
		}
		// new connection in connection pool created
	} catch (SQLException e) {
		System.out.println("Cannot create a new connection!");
		Rescon = null;
	}
	return rescon;
}
...

 

 

Also include the returnConnection() method, which returns a connection back to your storehouse and puts it at the end of the list:

 


...
public synchronized void returnConnection(Connection con) {
	if ((con != null) && (this.freeConnections.size() <= 
	this.maxconn)) {
		this.freeConnections.add(con);
	}
}
...

 

The last method from SimpleConnectionPool that you need to consider is release(), which closes and releases all connections from your connection pool:

 


...
public synchronized void release() {
	Iterator allc = this.freeConnections.iterator();
	while (allc.hasNext()) {
		Connection con = (Connection)allc.next();
		try {
			con.close();
		} catch (SQLException e) {
 			System.out.println("Cannot close connection! 
 			 (Probably already closed?)");
		}
	}
	this.freeConnections.clear();
}
...

 

 

Connection Pool in Practice
  To demonstrate an effective use of a connection pool, use a SimpleConnectionPool object in a standard servlet. The code is pretty easy and can be rewritten in JSP without any problems. The behavior of the servlet will be defined by the following methods:
  • init() — servlet creation and initialization
  • service() — control of received client requests
  • destroy() — servlet termination

The following code creates a SimpleConnectionPool object in init(), gets an available connection in service() with the getConnection() method, and releases the connection pool in the destroy() method:

 


// TestOurConnectionPoolServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestOurConnectionPoolServlet extends HttpServlet {
	
	private SimpleConnectionPool pool;
	
	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
		pool = SimpleConnectionPool.getInstance("jdbc:odbc:test", 
		"Administrator", "Admin", 30);
	}

	public void service(HttpServletRequest request, 
			   HttpServletResponse response) throws 
			   IOException {
		response.setContentType(text/html);
		PrintWriter out = response.getWriter();
		Connection con = pool.getConnection();
		if (con == null) {
			out.println("Can't receive connection!");
			return;
		}
		
		ResultSet rs = null;
		Statement stmt = null;
		ResultSetMetaData rsmd = null;

		try {
			stmt = con.createConnection();
			rs = stmt.executeQuery("SELECT * FROM Test");
			rsmd = rs.getMetaData();

			while(rs.next()) {
				for (int i = 1; i < rsmd.getColumnCount(); 
				i++) {
					out.print(rs.getString(i) + ", ");
				}
				out.println("");
			}
			stmt.close();
			rs.close();
		} catch (SQLException ex) {
			ex.printStackTrace(out);
		}
		pool.freeConnection(con);
	}

	public void destroy() {
		pool.release();
	}
}

 

 

Connection Pool: Essential for Large, Complex Web Applications
Although the code is easy, you obviously wouldn't use a connection pool in small Web applications. However, it is essential technology for large, complex applications. The example in this article shows the simplicity of a connection pool, as well as its programming solutions for dealing with database productivity and its methods for accessing databases. The important thing is to initialize the pool only once. You do not need to instantiate a new pool in each servlet or JSP. You can successfully apply connection pool technology to Internet shops or dynamic interactive sites, effectively using all your available resources.

 

 

 

This article originates from http://www.devx.com/Java/Article/20891/0/page/2

...
private SimpleConnectionPool(String URI, 
			      String dbuser, 
			      String dbpass,
			      String drivername, 
			      int maxconn) {
	this.URI = URI;
	this.dbuser = dbuser;
	this.dbpass = dbpass;
	this.drivername = drivername;
	this.maxconn = maxconn;

	loadJDBCDriver();
}
...

 

 

Because it's defined as private, you can't call SimpleConnectionPool from outside the class. You also need to define your constructor with an access modifier to be able to use the Singleton design pattern in this example. As you can see in the above code, after the constructor executes, you will have the variables set and the JDBC driver loaded.

The loadJDBCDriver() method is easy:

 


...
private void loadJDBCDriver() {
	try {
		Driver driver = (Driver)Class.forName(this.drivername).newInstance();
		DriverManager.registerDriver(driver);
	} catch (Exception e) {
		System.out.println("Can't load/register JDBC driver ");
	}
}
...
分享到:
评论

相关推荐

    The Java EE 6 Tutorial Basic Concepts 4th Edition

    DataSource Objects and Connection Pools 530 Resource Injection 531 Resource Adapters and Contracts 534 Metadata Annotations 538 Common Client Interface 540 Further Information about Resources 541...

    Java-ConnectionPools.rar_连接池

    Java数据库连接池是一种重要的资源管理技术,用于优化数据库应用程序的性能和效率。它通过复用已建立的数据库连接,避免了频繁创建和销毁连接带来的开销。以下是对压缩包文件中涉及的几个主要连接池组件的详细介绍:...

    JDBC驱动及JAR包

    JDBC(Java Database Connectivity)是Java编程语言中用于与各种数据库进行交互的一种标准接口。它由Sun Microsystems(现为Oracle公司)开发,旨在提供一种统一的方式,让Java开发者能够访问不同供应商的数据库系统...

    Microsoft IIS 6.0: Administrator's Pocket Consultant

    Manage Web applications, application pools, and Microsoft ASP.NET Configure SMTP, POP3, and advanced messaging options Implement security features—permissions, certificates and SSL Monitor and ...

    jdbc connection pool

    ### JDBC Connection Pool 实现 #### 一、简介 在Java应用程序中,数据库连接是非常宝贵的资源。为了提高性能和效率,通常会使用连接池技术来管理这些数据库连接。连接池可以复用现有的数据库连接,避免频繁地创建...

    JAVA操作数据库方式与设计模式应用.txt

    **JDBC(Java Database Connectivity)**是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了高度的抽象层,使得开发者可以通过统一的API来访问...

    Weblogic JDBC 数据源配置和详细参数说明

    要创建一个 JDBC 连接池,在 Administration Console 中右击 JDBC&gt;Connection Pools 节点,然后选择 Configure a new JDBC Connection Pool。这将显示一个 Configure a JDBC Connection Pool 画面。为 Oracle 数据库...

    JDBC连接oracle数据库[文].pdf

    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.96.1:1521:oracle9i", user, password); } catch (SQLException e) { return...

    配置BEA WebLogic 8.1 JDBC连接

    8. **配置JDBC连接池**:在WebLogic Server的管理控制台中,可以通过JDBC&gt;Connection Pools节点创建新的连接池。指定数据库类型、数据库驱动、连接属性等,如数据库名称、用户名、密码等。 9. **配置步骤**:在管理...

    JDBC连接oracle数据库.pdf

    1. **复制JDBC驱动文件**:从安装了Oracle数据库的服务器上的`Oracle安装目录/jdbc/lib/classes12.jar`文件复制到WEB发布服务器的一个目录中,例如`C:\`目录。 2. **设置CLASSPATH环境变量**:在系统的环境变量中...

    Java - The Well-Grounded Java Developer

    - **Overview**: Focuses on optimizing Java applications for better performance and resource utilization. - **Topics Covered**: - **Profiling Tools**: Introduction to profiling tools like VisualVM and...

    Weblogic 8.1中配置JDBC

    在WebLogic管理控制台中,导航到“Services Configurations” &gt; “JDBC” &gt; “Connection Pools”,然后点击“Configure a new JDBC Connection Pool…”开始配置连接池。在选择数据库类型时,由于例子中使用的是...

    weblogic4.pdf

    2. **新建连接池**:在[Connection Pools]页面,右键点击空白处,选择[Configure a new JDBC Connection Pool…],开始配置一个新的连接池。 3. **配置数据库驱动程序**:在配置向导中,需要指定数据库驱动程序的...

    JAVA基础加强 --学习心得一(JAVA中常用英文单词简写释义).pdf

    25. **DBCP (Database Connection Pools)**:数据库连接池是一种管理数据库连接的技术,提高数据库操作的效率。 26. **CGLIB (Code Generation Library)**:CGLIB是一个用于生成JAVA字节码的库,常用于AOP和ORM框架...

    InnovationPools:Innovation Pools网站

    在互联网的广阔海洋中,InnovationPools网站以其独特的创新理念和卓越的设计脱颖而出。... ...例如,使用、、、和等元素来划分页面的不同部分,提供更好的可访问性和用户体验。...通过使用媒体查询(media queries)和流式...

    JDBC连接Oracle数据库代码经验

    件中定义的连接池名字* @return Connection 可用的数据库连接*/public Connection getConnection(String name) throws SQLException {DBConnectionPool pool = (DBConnectionPool) pools.get(name);if (pool != null...

    Portal Server Guide

    - Set up the database schema and configure connection pools. 5. **Portal Configuration**: - Define the portal structure, including pages, portlets, and navigation elements. - Customize the look ...

    Java名词解释

    DBCP(Database Connection Pools)是数据库连接池,用于管理数据库连接,提高性能。 SOAP(Simple Object Access Protocol)是简单的对象访问协议,常用于Web服务。SOA(Service-Oriented Architecture)面向服务...

    db_connection:数据库连接行为

    $ mix test.pools 要运行所有测试: $ mix test.all 设计 该库由四个主要模块组成: DBConnection这是在客户端上运行的代码以及DBConnection API的规范 DBConnection.Connection这是建立数据库连接的过程 ...

Global site tag (gtag.js) - Google Analytics