proxool 配置

资料来源:  http://sunnylocus.iteye.com/blog/359570

  proxool一个数据库连接池框架,提供了对你选择的其它类型的驱动程序的连接池封装。可以非常简单的移植到现存的代码中。完全可配置。快速,成熟,健壮。可以透明地为你现存的JDBC驱动程序增加连接池功能。到目前为止最新版本是proxool 0.9.1,可从官网下载最新版本http://proxool.sourceforge.net


一、配置proxool.xml文件

<?xml version="1.0" encoding="UTF-8"?>
    <!--
        the proxool configuration can be embedded within your own
        application's. Anything outside the "proxool" tag is ignored.
    -->
<something-else-entirely>
    <proxool>
        <alias>dbname</alias> <!--数据源的别名-->
        <driver-url>jdbc:oracle:thin:@127.0.0.1:1521:testdb</driver-url><!--url连接串-->
        <driver-class>oracle.jdbc.driver.OracleDriver</driver-class> <!--驱动类-->
        <driver-properties>
            <property name="user" value="username" /> <!--用户名-->
            <property name="password" value="password" /><!--密码-->
        </driver-properties>
        <!--最大连接数(默认5个),超过了这个连接数,再有请求时,就排在队列中等候,最大的等待请求数由maximum-new-connections决定 -->
        <maximum-connection-count>100</maximum-connection-count>
        <!--最小连接数(默认2个)-->
        <minimum-connection-count>10</minimum-connection-count>
        <!--proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒-->
        <house-keeping-sleep-time>90000</house-keeping-sleep-time>
        <!--没有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受-->
        <maximum-new-connections>10</maximum-new-connections>
        <!--最少保持的空闲连接数(默认2个)-->
        <prototype-count>5</prototype-count>
        <!--在使用之前测试-->
        <test-before-use>true</test-before-use>
        <!--用于保持连接的测试语句 -->
        <house-keeping-test-sql>select sysdate from dual</house-keeping-test-sql>
    </proxool>
</something-else-entirely> 



二、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
  <servlet-name>ServletConfigurator</servlet-name>
  <servlet-class>
    org.logicalcobwebs.proxool.configuration.ServletConfigurator
  </servlet-class>
  <init-param>
    <param-name>xmlFile</param-name>
    <param-value>WEB-INF/proxool.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>Admin</servlet-name>
  <servlet-class>
    org.logicalcobwebs.proxool.admin.servlet.AdminServlet
  </servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Admin</servlet-name>
  <url-pattern>/admin</url-pattern>
</servlet-mapping>
<!-- 配置受保护域,只有Tomcat管理员才能察看连接池的信息 -->
<security-constraint>
  <web-resource-collection>
      <web-resource-name>proxool</web-resource-name>
      <url-pattern>/admin</url-pattern>
  </web-resource-collection>
  <auth-constraint>
     <role-name>manager</role-name>
     </auth-constraint>
  </security-constraint>
 <login-config>
     <auth-method>BASIC</auth-method>
     <realm-name>proxool manager Application</realm-name>
  </login-config>
  <security-role>
    <description>The role that is required to log in to the Manager Application</description>
     <role-name>manager</role-name>
 </security-role>
  <error-page>
    <error-code>401</error-code>
    <location>/401.jsp</location>
  </error-page>
</web-app>



 

ServletConfigurator:加载并初始化proxool.xml文件,因为它是连接数据库的.其他很多模块都用到数据,所以必须首先加载它
load-on-startup:数值越小,就会先被加载初始化

Admin:监控数据库连接池的连接情况

//获得数据库连接的语句

Connection conn=DriverManager.getConnection("proxool.dbname");

 

 

注意:在401.jsp页面中必须加

<%
  response.setHeader("WWW-Authenticate", "Basic realm=\"Tomcat Manager Application\"");
%>这句话,否则在访问/admin察看连接池信息时,会直接跳转到401.jsp页面。我们是想让访问admin/的用户必须输入用户名和密码,且必须是manager角色,三次输入不正确才会跳到401.jsp页面,如图


proxool 配置_第1张图片

输入正确用户名和密码后才能看到proxool池的信息

http://sunnylocus.iteye.com/upload/picture/pic/34529/d9240b55-37c3-3eac-83c1-cb6aeb6a61aa.jpg  


三、更详细的proxool.xml的配置属性说明:

 <?xml version="1.0" encoding="ISO-8859-1"?>
<!--
Properties for Proxool Configurator testing. Defines the same parameters as
TestHelper.buildCompleteAlternativeProperties()
-->
<something-else-entirely xmlns="http://sumthin.else.entirely" xmlns:proxool="The latest version is available at http://proxool.sourceforge.net/xml-namespace">
    <proxool:proxool>
        <proxool:alias>xml-test-ns</proxool:alias>
        <proxool:driver-url>jdbc:hsqldb:db/test</proxool:driver-url>
        <proxool:driver-class>org.hsqldb.jdbcDriver</proxool:driver-class>
        <proxool:driver-properties>
            <proxool:property name="user" value="sa"/>
            <proxool:property name="password" value=""/>
        </proxool:driver-properties>
        <proxool:house-keeping-sleep-time>40000</proxool:house-keeping-sleep-time>
        <proxool:house-keeping-test-sql>select CURRENT_DATE</proxool:house-keeping-test-sql>
        <proxool:maximum-connection-count>10</proxool:maximum-connection-count>
        <proxool:minimum-connection-count>3</proxool:minimum-connection-count>
        <proxool:maximum-connection-lifetime>18000000</proxool:maximum-connection-lifetime> <!-- 5 hours -->
        <proxool:simultaneous-build-throttle>5</proxool:simultaneous-build-throttle>
        <proxool:recently-started-threshold>40000</proxool:recently-started-threshold>
        <proxool:overload-without-refusal-lifetime>50000</proxool:overload-without-refusal-lifetime>
        <proxool:maximum-active-time>60000</proxool:maximum-active-time>
        <proxool:verbose>true</proxool:verbose>
        <proxool:trace>true</proxool:trace>
        <proxool:fatal-sql-exception>Fatal error</proxool:fatal-sql-exception>
        <proxool:prototype-count>2</proxool:prototype-count>
    </proxool:proxool>
    <nothing-to-do-with-proxool>
        <proxool:proxool>
            <proxool:alias>xml-test-ns-2</proxool:alias>
            <proxool:driver-url>jdbc:hsqldb:db/test</proxool:driver-url>
            <proxool:driver-class>org.hsqldb.jdbcDriver</proxool:driver-class>
            <proxool:driver-properties>
                <proxool:property name="user" value="sa"/>
                <proxool:property name="password" value=""/>
            </proxool:driver-properties>
            <proxool:house-keeping-sleep-time>40000</proxool:house-keeping-sleep-time>
            <proxool:house-keeping-test-sql>select CURRENT_DATE</proxool:house-keeping-test-sql>
            <proxool:maximum-connection-count>10</proxool:maximum-connection-count>
            <proxool:minimum-connection-count>3</proxool:minimum-connection-count>
            <proxool:maximum-connection-lifetime>18000000</proxool:maximum-connection-lifetime> <!-- 5 hours -->
            <proxool:simultaneous-build-throttle>5</proxool:simultaneous-build-throttle>
            <proxool:recently-started-threshold>40000</proxool:recently-started-threshold>
            <proxool:overload-without-refusal-lifetime>50000</proxool:overload-without-refusal-lifetime>
            <proxool:maximum-active-time>60000</proxool:maximum-active-time>
            <proxool:verbose>true</proxool:verbose>
            <proxool:trace>true</proxool:trace>
            <proxool:fatal-sql-exception>Fatal error</proxool:fatal-sql-exception>
            <proxool:prototype-count>2</proxool:prototype-count>
        </proxool:proxool>
    </nothing-to-do-with-proxool>
</something-else-entirely>



属性列表说明:

fatal-sql-exception: 它是一个逗号分割的信息片段.当一个SQL异常发生时,他的异常信息将与这个信息片段进行比较.如果在片段中存在,那么这个异常将被认为是个致命错误(Fatal SQL Exception ).这种情况下,数据库连接将要被放弃.无论发生什么,这个异常将会被重掷以提供给消费者.用户最好自己配置一个不同的异常来抛出.

fatal-sql-exception-wrapper-class:正如上面所说,你最好配置一个不同的异常来重掷.利用这个属性,用户可以包装SQLException,使他变成另外一个异常.这个异常或者继承SQLException或者继承字RuntimeException.proxool自带了2个实现:'org.logicalcobwebs.proxool.FatalSQLException' 和'org.logicalcobwebs.proxool.FatalRuntimeException' .后者更合适.

house-keeping-sleep-time: house keeper 保留线程处于睡眠状态的最长时间,house keeper 的职责就是检查各个连接的状态,并判断是否需要销毁或者创建.

house-keeping-test-sql:  如果发现了空闲的数据库连接.house keeper 将会用这个语句来测试.这个语句最好非常快的被执行.如果没有定义,测试过程将会被忽略。

injectable-connection-interface: 允许proxool实现被代理的connection对象的方法.

injectable-statement-interface: 允许proxool实现被代理的Statement 对象方法.

injectable-prepared-statement-interface: 允许proxool实现被代理的PreparedStatement 对象方法.

injectable-callable-statement-interface: 允许proxool实现被代理的CallableStatement 对象方法.

jmx:

jmx-agent-id:

jndi-name: 数据源的名称

maximum-active-time: 如果housekeeper 检测到某个线程的活动时间大于这个数值.它将会杀掉这个线程.所以确认一下你的服务器的带宽.然后定一个合适的值.默认是5分钟.

maximum-connection-count: 最大的数据库连接数.

maximum-connection-lifetime: 一个线程的最大寿命.

minimum-connection-count: 最小的数据库连接数

overload-without-refusal-lifetime:

prototype-count: 连接池中可用的连接数量.如果当前的连接池中的连接少于这个数值.新的连接将被建立(假设没有超过最大可用数).例如.我们有3个活动连接2个可用连接,而我们的prototype-count是4,那么数据库连接池将试图建立另外2个连接.这和 minimum-connection-count不同. minimum-connection-count把活动的连接也计算在内.prototype-count 是spare connections 的数量.

recently-started-threshold:  略

simultaneous-build-throttle:  略

statistics: 连接池使用状况统计。 参数“10s,1m,1d”

statistics-log-level:  日志统计跟踪类型。 参数“ERROR”或 “INFO”

test-before-use:

test-after-use:

trace: 如果为true,那么每个被执行的SQL语句将会在执行期被log记录(DEBUG LEVEL).你也可以注册一个ConnectionListener (参看ProxoolFacade)得到这些信息.

verbose: 详细信息设置。 参数 bool 值


------------------------------------------------------------------------------------------------------


1.	在WEB-INF中建立proxool.xml 
    <?xml version="1.0" encoding="UTF-8"?>
  <proxool>
    <alias>DBPool</alias>   <!--这里是连接池的别名-->
    <driver-url>jdbc:sqlserver://localhost:1433;DatabaseName=test</driver-url>
    <driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
    <driver-properties>
      <property name="user" value="sa"/>
      <property name="password" value="sa1234"/>
    </driver-properties>
     <!-- 自动侦察各个连接状态的时间间隔(毫秒,侦察到空闲的连接就马上回收,超时的销毁 -->
    <house-keeping-sleep-time>90000</house-keeping-sleep-time>
    <!-- 最大的等待请求数,即因没有空闲连接可以分配而在队列中等待的最大请求数,超过这个请求数的,用户连接就不会被接受 -->
    <proxool.simultaneous-build-throttle>20</proxool.simultaneous-build-throttle>
    <!-- 最少保持的空闲连接数 -->
    <prototype-count>1</prototype-count>
    <!-- 允许最在连接数,超过了这个连接,再有请求时,就排在队列中 -->
    <maximum-connection-count>1</maximum-connection-count>
    <!-- 最小连接数 -->
    <minimum-connection-count>1</minimum-connection-count>
    <!-- 如果发现了空闲的数据库连接.house keeper 将会用这个语句来测试.这个语句最好非常快的被执行.如果没有定义,测试过程将会被忽略。 -->
    <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql>
  </proxool>

2.	在web.xml加监听
   <!-- proxool 数据连接池 -->
  <servlet>
     <servlet-name>proxoolServletConfigurator</servlet-name>
 <servlet-class>org.logicalcobwebs.proxool.configuration.ServletConfigurator</servlet-class>
     <init-param>
       <param-name>xmlFile</param-name>
       <param-value>WEB-INF/proxool.xml</param-value><!--这里对应刚才建立的xml配置文件名-->
     </init-param>
     <load-on-startup>1</load-on-startup>
   </servlet>
<!-- proxool提供的管理监控工具,可查看当前数据库连接情况-->
   <servlet>
    <servlet-name>Admin</servlet-name>
      <servlet-class>org.logicalcobwebs.proxool.admin.servlet.AdminServlet</servlet-class>
   </servlet>
   <servlet-mapping>
    <servlet-name>Admin</servlet-name>
    <url-pattern>/admin</url-pattern>
   </servlet-mapping>

3.	jsp测试
  <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@page import="java.sql.*"%>
<%@page contentType="text/html; charset=GBK"%>
<%@page import="test.*"%>

<html>
<head>
<title>ProxoolTest</title>
</head>
<body bgcolor="#ffffff">
<h1>Proxool连接池测试</h1>
<%
  Connection con = null;
  Statement stmt = null;
  ResultSet rs = null;
  try {
    con = DriverManager.getConnection("proxool.DBPool");
    stmt = con.createStatement();

    String query = "select * from test t";
    out.println("query:" + query+ "--OK<br/>");
    rs = stmt.executeQuery(query);
    out.println("rs.next():" + rs.next()+ "--OK<br/>");
  
    while (rs.next()) {
      out.println(rs.getString(3) + "--OK<br/>");
    }
  }
  catch (SQLException sqle) {
    out.println("sqle=" + sqle+ "--OK<br/>");
  }
  finally {
    try {
      rs.close();
      stmt.close();
      if (con != null) {
        con.close();
      }
    }
    catch (SQLException sqle) {
      out.println("sqle=" + sqle+ "--OK<br/>");
    }
  }
%>
</body>
</html>

4.	main测试
      
  
import java.sql.Connection;   
import java.sql.DriverManager;   
import java.sql.ResultSet;   
import java.sql.Statement;   
  
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;   
  
public class TestProxool {   
    // public static String dburl =   
    // "jdbc:oracle:thin:@192.168.104.192:1521:tim";   
    public static String dburl = "jdbc:sqlserver://localhost:1433;DatabaseName=test";   
    public static String user = "sa";   
    public static String password = "sa1234";   
  
    /**  
     * JDBC方式测试  
     *   
     * @throws Exception  
     */  
    public static void test1() throws Exception {   
        String testsql = "select * from test";   
        // 1:注册驱动类   
        // Class.forName("oracle.jdbc.driver.OracleDriver");   
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");   
        // 2:创建数据库连接   
        Connection conn = DriverManager.getConnection(dburl, user, password);   
        // 3:创建执行SQL的对象   
        Statement stmt = conn.createStatement();   
        // 4:执行SQL,并获取返回结果   
        ResultSet rs = stmt.executeQuery(testsql);   
        // 5:处理返回结果,此处打印查询结果   
        while (rs.next()) {   
            System.out.print(rs.getString("a") + "\t");   
            // System.out.print(rs.getString("name") + "\t");   
            System.out.println();   
        }   
        // 6:关闭数据库连接   
        conn.close();   
    }   
  
    /**  
     * proxool方式测试  
     *   
     * @throws Exception  
     */  
    public static void test2() throws Exception {   
        // Java应用中先要加载配置文件,否则谁知道你配置给谁用的   
        JAXPConfigurator.configure("D:\\workspace\\PoolTest\\src\\proxool.xml",   false);   
        String testsql = "select * from test";   
        // 1:注册驱动类,这次这个驱动已经不是Oracle的驱动了,是Proxool专用的驱动   
        Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");   
        // 2:创建数据库连接,这个参数是一个字符串,是数据源的别名,在配置文件中配置的DBPool,参数格式为:proxool.数据源的别名   
        Connection conn = DriverManager.getConnection("proxool.DBPool");   
        // 3:创建执行SQL的对象   
        Statement stmt = conn.createStatement();   
        // 4:执行SQL,并获取返回结果   
        ResultSet rs = stmt.executeQuery(testsql);   
        // 5:处理返回结果,此处打印查询结果   
        while (rs.next()) {   
            System.out.print(rs.getString("e") + "\t");   
            // System.out.print(rs.getString("name") + "\t");   
            System.out.println();   
        }   
        // 6:关闭数据库连接   
        conn.close();   
    }   
  
    public static void main(String[] args) throws Exception {   
         //test1();   
        test2();  
    	    	
    }   
}  


5.	java+jsp
(1)java代码
  package test;

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

import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.admin.SnapshotIF;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;

public class PoolManager {

	private static int activeCount = 0;

	public PoolManager() {

	}

	/**
	 * * 获取连接 * getConnection *
	 * 
	 * @param name
	 * 
	 * @return
	 */
	public Connection getConnection() {
		try {
			// JAXPConfigurator.configure("D:\\workspace\\PoolTest\\src\\proxool.xml",
			// false);
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");// proxool驱动类
			Connection conn = DriverManager.getConnection("proxool.DBPool");
			// 此处的DBPool是在proxool.xml中配置的连接池别名
			showSnapshotInfo();

			return conn;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 此方法可以得到连接池的信息 * showSnapshotInfo
	 */
	private void showSnapshotInfo() {
		try {
			SnapshotIF snapshot = ProxoolFacade.getSnapshot("DBPool", true);
			int curActiveCount = snapshot.getActiveConnectionCount();// 获得活动连接数
			int availableCount = snapshot.getAvailableConnectionCount();// 获得可得到的连接数
			int maxCount = snapshot.getMaximumConnectionCount();// 获得总连接数
			if (curActiveCount != activeCount)// 当活动连接数变化时输出的信息
			{
				System.out.println("活动连接数:" + curActiveCount
						+ "(active)  可得到的连接数:" + availableCount
						+ "(available)  总连接数:" + maxCount + "(max)");
				activeCount = curActiveCount;
			}
		} catch (ProxoolException e) {
			e.printStackTrace();
		}
	}

	/**
	 * * 获取连接  
	 * * getConnection  *
	 * 
	 * @param name
	 *         
	 * @return 
	 */
	public Connection getConnection(String name) {
		return getConnection();
	}

	/**
	 *  * 释放连接  * freeConnection  *
	 * 
	 * @param conn
	 *          
	 */
	public void freeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * * 释放连接  * freeConnection  *
	 * 
	 * @param name
	 *           *
	 * @param con
	 *          
	 */
	public void freeConnection(String name, Connection con) {
		freeConnection(con);
	}

	public void getQuery() {
		try {
			Connection conn = getConnection();
			if (conn != null) {
				Statement statement = conn.createStatement();
				ResultSet rs = statement.executeQuery("select * from test");
				int c = rs.getMetaData().getColumnCount();
				while (rs.next()) {
					System.out.println();
					for (int i = 1; i <= c; i++) {
						System.out.print(rs.getObject(i));
					}
				}
				rs.close();
			}
			freeConnection(conn);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
(2)jsp代码
   <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@page import="java.sql.*"%>
<%@page contentType="text/html; charset=GBK"%>
<%@page import="test.*"%>

<html>
	<head>
		<title>ProxoolTest</title>
	</head>
	<body bgcolor="#ffffff">
		<h1>
			Proxool连接池测试
		</h1>
		<%
			Connection con = null;
			try {
				PoolManager poo = new PoolManager();
				//con =poo.getConnection();
				poo.getQuery();
			} catch (Exception sqle) {
				out.println("sqle=" + sqle + "--OK<br/>");
			} finally {

			}
		%>
	</body>
</html>





 

你可能感兴趣的:(exception,数据库,String,数据库连接池,sqlserver,import)