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

前几篇中有说使用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);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Tomcat中配置数据库连接,可以按照以下步骤进行操作: 1. 首先,确保你已经将数据库的驱动程序(JDBC驱动)复制到Tomcat的`lib`目录下。这通常是将JDBC驱动的JAR文件放置在`$CATALINA_HOME/lib`目录中。 2. 在Tomcat的`conf`目录下创建一个新的文件夹(如果文件夹不存在),并命名为`Catalina`。在`Catalina`文件夹下创建一个新的文件夹,并以你的应用程序的上下文路径命名(例如:如果你的应用程序部署在 `/myapp` 路径下,那么就创建一个名为 `myapp` 的文件夹)。 3. 在上一步创建的文件夹中创建一个名为 `META-INF` 的新文件夹。在 `META-INF` 文件夹中创建一个名为 `context.xml` 的文件,用于配置数据库连接。 4. 打开 `context.xml` 文件,在其中添加以下内容: ```xml <Context> <Resource name="jdbc/yourDatabaseName" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="yourUsername" password="yourPassword" driverClassName="yourDriverClass" url="yourJdbcUrl"/> </Context> ``` 请注意替换上述代码中的以下值: - `yourDatabaseName`:要使用的数据库名称。 - `yourUsername`:连接数据库所需的用户名。 - `yourPassword`:连接数据库所需的密码。 - `yourDriverClass`:数据库驱动程序的类名。 - `yourJdbcUrl`:数据库的JDBC连接URL。 你可以根据需要调整上述代码中的其他属性,如 `maxActive`(最大活动连接数)、`maxIdle`(最大空闲连接数)和 `maxWait`(最长等待连接的时间)。 5. 保存并关闭 `context.xml` 文件。 6. 重新启动Tomcat服务器,使配置生效。 现在,你已经成功配置了Tomcat中的数据库连接。你可以在应用程序中使用 `java:/comp/env/jdbc/yourDatabaseName` JNDI名称来获取数据库连接

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值