通过tomact服务器配置文件创建链接池

原创 2013年12月03日 14:34:48

前几篇中有说使用DBCP,C3P0和自定义方法创建数据库链接池,这里还有另外一种方法,即通过Tomcat服务器来创建连接池。

Tomcat服务器创建的数据库链接池,其自身也是通过DBCP来创建的。Tomcat服务器是通过在<context>中来配置一个Jndi容器,使这个链接池绑定到一个Jndi容器中,同时将她关联到一个名称上,code中通过查找Jndi容器来获取这个链接池。

下面是从Tomcat 文档截下来的,详细告诉了怎么配置和怎么在code中获取。

JNDI Resources HOW-TO

JDBC Data Sources

0. Introduction

Many web applications need to access a database via a JDBC driver, to support the functionality required by that application. The Java EE Platform Specification requires Java EE Application Servers to make available a DataSource implementation (that is, a connection pool for JDBC connections) for this purpose. Tomcat offers exactly the same support, so that database-based applications you develop on Tomcat using this service will run unchanged on any Java EE server.

For information about JDBC, you should consult the following:

NOTE - The default data source support in Tomcat is based on the DBCP connection pool from the Commons project. However, it is possible to use any other connection pool that implements javax.sql.DataSource, by writing your own custom resource factory, as described below.

1. Install Your JDBC Driver

Use of the JDBC Data Sources JNDI Resource Factory requires that you make an appropriate JDBC driver available to both Tomcat internal classes and to your web application. This is most easily accomplished by installing the driver's JAR file(s) into the $CATALINA_HOME/lib directory, which makes the driver available both to the resource factory and to your application.

2. Declare Your Resource Requirements

Next, modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured data source. By convention, all such names should resolve to the jdbc subcontext (relative to the standard java:comp/env naming context that is the root of all provided resource factories. A typical web.xml entry might look like this:

<resource-ref>
  <description>
    Resource reference to a factory for java.sql.Connection
    instances that may be used for talking to a particular
    database that is configured in the <Context>
    configurartion for the web application.
  </description>
  <res-ref-name>
    jdbc/EmployeeDB
  </res-ref-name>
  <res-type>
    javax.sql.DataSource
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>

WARNING - Be sure you respect the element ordering that is required by the DTD for web application deployment descriptors! See the Servlet Specification for details.

3. Code Your Application's Use Of This Resource

A typical use of this resource reference might look like this:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
  envCtx.lookup("jdbc/EmployeeDB");

Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();

Note that the application uses the same resource reference name that was declared in the web application deployment descriptor. This is matched up against the resource factory that is configured in the <Context> element for the web application as described below.

4. Configure Tomcat's Resource Factory

To configure Tomcat's resource factory, add an element like this to the <Context> element for the web application.

<Context ...>
  ...
  <Resource name="jdbc/EmployeeDB"
            auth="Container"
            type="javax.sql.DataSource"
            username="dbusername"
            password="dbpassword"
            driverClassName="org.hsql.jdbcDriver"
            url="jdbc:HypersonicSQL:database"
            maxActive="8"
            maxIdle="4"/>
  ...
</Context>

Note that the resource name (here, jdbc/EmployeeDB) must match the value specified in the web application deployment descriptor.

This example assumes that you are using the HypersonicSQL database JDBC driver. Customize the driverClassName and driverName parameters to match your actual database's JDBC driver and connection URL.

The configuration properties for Tomcat's standard data source resource factory (org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory) are as follows:

  • driverClassName - Fully qualified Java class name of the JDBC driver to be used.
  • username - Database username to be passed to our JDBC driver.
  • password - Database password to be passed to our JDBC driver.
  • url - Connection URL to be passed to our JDBC driver. (For backwards compatibility, the property driverName is also recognized.)
  • initialSize - The initial number of connections that will be created in the pool during pool initialization. Default: 0
  • maxActive - The maximum number of connections that can be allocated from this pool at the same time. Default: 8
  • minIdle - The minimum number of connections that will sit idle in this pool at the same time. Default: 0
  • maxIdle - The maximum number of connections that can sit idle in this pool at the same time. Default: 8
  • maxWait - The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception. Default: -1 (infinite)

Some additional properties handle connection validation:

  • validationQuery - SQL query that can be used by the pool to validate connections before they are returned to the application. If specified, this query MUST be an SQL SELECT statement that returns at least one row.
  • validationQueryTimeout - Timeout in seconds for the validation query to return. Default: -1 (infinite)
  • testOnBorrow - true or false: whether a connection should be validated using the validation query each time it is borrowed from the pool. Default: true
  • testOnReturn - true or false: whether a connection should be validated using the validation query each time it is returned to the pool. Default: false

The optional evictor thread is responsible for shrinking the pool by removing any conections which are idle for a long time. The evictor does not respect minIdle. Note that you do not need to activate the evictor thread if you only want the pool to shrink according to the configured maxIdle property.

The evictor is disabled by default and can be configured using the following properties:

  • timeBetweenEvictionRunsMillis - The number of milliseconds between consecutive runs of the evictor. Default: -1 (disabled)
  • numTestsPerEvictionRun - The number of connections that will be checked for idleness by the evitor during each run of the evictor. Default: 3
  • minEvictableIdleTimeMillis - The idle time in milliseconds after which a connection can be removed from the pool by the evictor. Default: 30*60*1000 (30 minutes)
  • testWhileIdle - true or false: whether a connection should be validated by the evictor thread using the validation query while sitting idle in the pool. Default: false

Another optional feature is the removal of abandoned connections. A connection is called abandoned if the application does not return it to the pool for a long time. The pool can close such connections automatically and remove them from the pool. This is a workaround for applications leaking connections.

The abandoning feature is disabled by default and can be configured using the following properties:

  • removeAbandoned - true or false: whether to remove abandoned connections from the pool. Default: false
  • removeAbandonedTimeout - The number of seconds after which a borrowed connection is assumed to be abandoned. Default: 300
  • logAbandoned - true or false: whether to log stack traces for application code which abandoned a statement or connection. This adds serious overhead. Default: false

Finally there are various properties that allow further fine tuning of the pool behaviour:

  • defaultAutoCommit - true or false: default auto-commit state of the connections created by this pool. Default: true
  • defaultReadOnly - true or false: default read-only state of the connections created by this pool. Default: false
  • defaultTransactionIsolation - This sets the default transaction isolation level. Can be one of NONE, READ_COMMITTED, READ_UNCOMMITTED, REPEATABLE_READ, SERIALIZABLE. Default: no default set
  • poolPreparedStatements - true or false: whether to pool PreparedStatements and CallableStatements. Default: false
  • maxOpenPreparedStatements - The maximum number of open statements that can be allocated from the statement pool at the same time. Default: -1 (unlimited)
  • defaultCatalog - The name of the default catalog. Default: not set
  • connectionInitSqls - A list of SQL statements run once after a Connection is created. Separate multiple statements by semicolons (;). Default: no statement
  • connectionProperties - A list of driver specific properties passed to the driver for creating connections. Each property is given as name=value, multiple properties are separated by semicolons (;). Default: no properties
  • accessToUnderlyingConnectionAllowed - true or false: whether accessing the underlying connections is allowed. Default: false

For more details, please refer to the commons-dbcp documentation.

需要注意的地方是,数据库驱动jar包需要放在Tomcat服务器自身的lib文件中,即$CATALINA_HOME/lib directory目录下。



下面是一个例子:

//TomcatJndiPool 类,工具类,提供getConnection 和release方法,getConnection会从链接池中返回一个数据库链接。release方法会在不使用这个链接时,将这个链接返回到链接池中。


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class JndiPools {

public static Connection getConnection(){
Connection conn = null;
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env"); //获取Jndi容器
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB"); //从Jndi容器中获取数据库链接池

return conn = ds.getConnection();
}catch(Exception e){
throw new ExceptionInInitializerError(e);
}

}

public static void release(Connection conn, Statement st, ResultSet rs) {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}

if(st != null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
st = null;
}

if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}

}


//配置文件context.xml,此配置文件可以放在tomcat server.xml中,也可以放在META-INF 下

--WebRoot

--META-INF

--context.xml

其内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/EmployeeDB"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jdbc"
maxActive="8"
maxIdle="4"/>
</Context>


//demo


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import cn.itcast.utils.JndiPools;

public class JndiPoolDemo {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

@Test
public void query() {
try {
conn = JndiPools.getConnection();
String sql = "select name, money from account";

ps = conn.prepareStatement(sql);

rs = ps.executeQuery();
while (rs.next()) {
System.out.print("name:--" + rs.getString("name"));
System.out.println("money:" + rs.getFloat("money"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JndiPools.release(conn, ps, rs);
}
}
}

SQL Server中创建Oracle的链接服务器

打开Microsoft SQL Server Management Studio并以sa身份登录,在左侧的“对象资源管理器”窗口中展开“服务器对象”节点,在其下的“链接服务器”节点上右键选择“新建链接...
  • m15188153014
  • m15188153014
  • 2015年12月24日 16:49
  • 597

SQL创建链接服务器(脚本)

if exists (select * from master.dbo.sysservers where srvname = 'srv_lnk')     exec sp_dropserver 'sr...
  • markloong
  • markloong
  • 2015年06月05日 17:45
  • 1802

SQL 添加链接服务器

exec sp_catalogs srv_lnk --创建链接服务器 exec sp_addlinkedserver 'srv_lnk','','SQLOLEDB','远程服务器名或ip地址' ...
  • tianlianchao1982
  • tianlianchao1982
  • 2014年12月22日 10:05
  • 1575

Tomact中的类加载路径

学习Tomact很长时间了,还是对Tomact整个的类加载过程不太明白。今天就来总结一下,其实非常的简单。  首先看一下Tomact的目录结构   目录 描述 /bin 存放在Win...
  • ZHOUCHAOQIANG
  • ZHOUCHAOQIANG
  • 2015年10月11日 19:59
  • 1690

血泪经验分享--->SQL Server 2012建立链接服务器

现在我有一个需求是需要在两个不同的SQL SERVER 2012的服务器之间进行数据访问和更新。我们需要把Server One的数据插入到Server Two的服务器上去,一天执行一次任务。我们的首选...
  • waterxcfg304
  • waterxcfg304
  • 2014年12月19日 09:56
  • 26491

VMware vSphere 服务器虚拟化之二十二桌面虚拟化之创建View Composer链接克隆的虚拟桌面池

VMware vSphere 服务器虚拟化之二十二桌面虚拟化之创建View Composer链接克隆的虚拟桌面池     在上一节我们创建了完整克隆的自动专有桌面池,在创建过程比较缓慢,这次我们将...
  • kkfloat
  • kkfloat
  • 2013年07月06日 13:37
  • 7435

jedis连接池详解(Redis)

原子性(atomicity):一个事务是一个不可分割的最小工作单位,事务中包括的诸操作要么都做,要么都不做。Redis所有单个命令的执行都是原子性的,这与它的单线程机制有关;Redis命令的原子性使得...
  • jethai
  • jethai
  • 2016年08月28日 14:01
  • 3382

ACE+线程池实现一个简单的服务器+多客户端通信程序

ACE中本身具有异步通信组建,比如handle_input和handle_ouput等方法,可以用来实现一个 单线程的服务器,并且可以...
  • j_akill
  • j_akill
  • 2014年09月27日 23:50
  • 2899

Tomact的一些小配置

1、当一台服务器启动太大的Tomact的时候,需要区别Tomact
  • liuyuehu
  • liuyuehu
  • 2014年08月08日 11:42
  • 2550

Tomact服务器配置实现app更新

1、配置Java运行环境 从官网上下载最新的JDK:http://java.sun.com/javase/downloads/index.jsp ,下载后安装,选择想把JDK安装到的目录。JRE是包...
  • u014600432
  • u014600432
  • 2015年11月16日 12:50
  • 915
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:通过tomact服务器配置文件创建链接池
举报原因:
原因补充:

(最多只允许输入30个字)