论坛首页 入门技术论坛

持久层动态创建、启动、停止和使用多个数据源的方法

浏览 2318 次
该帖已经被评为新手帖
作者 正文
   发表时间:2011-06-29  
本文介绍bbossgroups 持久层框架动态创建、启动、停止和使用多个数据源的方法,直接看代码,欢迎大家一起讨论,有疑问可相互交流。
@Test
    public void stopPool()
    {
        try {
			DBUtil.stopPool(null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @Test
    public void startPool()
    {
        try {
        	DBUtil.getJDBCPoolMetaData(null);
			DBUtil.startPool(null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Test
    public void testExternalMeta()
    {
        try {
        	DBUtil.startPool(null);
        	JDBCPoolMetaData meta = DBUtil.getJDBCPoolMetaData("mq");
        	JDBCPool pool = DBUtil.getPool("mq");
        	PoolmanStatic sss = new PoolmanStatic();
        	TransferObjectFactory.createTransferObject(meta, sss);
        	System.out.println(pool.getStartTime());
        	System.out.println(pool.getStopTime());
        	System.out.println(pool.getStatus());
        	sss.isExternal();
        	DBUtil.stopPool("bspf");
        	System.out.println(pool.getStartTime());
        	System.out.println(pool.getStopTime());
        	System.out.println(pool.getStatus());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    @Test
    public void testMeta()
    {
        try {
        	DBUtil.startPool(null);
        	JDBCPoolMetaData meta = DBUtil.getJDBCPoolMetaData("bspf");
        	JDBCPool pool = DBUtil.getPool("bspf");
        	PoolmanStatic sss = new PoolmanStatic();
        	TransferObjectFactory.createTransferObject(meta, sss);
        	System.out.println(pool.getStartTime());
        	System.out.println(pool.getStopTime());
        	System.out.println(pool.getStatus());
        	sss.isExternal();
        	DBUtil.stopPool("bspf");
        	PreparedDBUtil db = new PreparedDBUtil();
    		db.preparedSelect("Select 1 from dual");
    		db.executePrepared();
        	System.out.println(pool.getStartTime());
        	System.out.println(pool.getStopTime());
        	System.out.println(pool.getStatus());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
     
    
    @Test
    public void startstopExterPool()
    {
        try {
        	
//			DBUtil.stopPool("mq");
			System.out.println("DBUtil.statusCheck(\"mq\"):"+DBUtil.statusCheck("mq"));
			System.out.println("DBUtil.statusCheck(\"bspf\"):"+DBUtil.statusCheck("bspf"));
			System.out.println("DBUtil.statusCheck(\"kettle\"):"+DBUtil.statusCheck("kettle"));
			DBUtil dbutil= new DBUtil();
			try {
				
				dbutil.executeSelect("mq", "Select 1 from dual");
				System.out.println("dbutil.size():" + dbutil.size());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			DBUtil.startPool("mq");
			dbutil = new DBUtil();
			dbutil.executeSelect("mq","Select 1 from dual");
    		System.out.println("dbutil.size():" + dbutil.size());
			System.out.println("DBUtil.statusCheck(\"mq\"):"+DBUtil.statusCheck("mq"));
			System.out.println("DBUtil.statusCheck(\"bspf\"):"+DBUtil.statusCheck("bspf"));
			System.out.println("DBUtil.statusCheck(\"kettle\"):"+DBUtil.statusCheck("kettle"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @Test
	public void testStartPool()
	{
    	TransactionManager tm = new TransactionManager();
    	try
    	{
    		DBUtil dbutil = new DBUtil();
    		String name = "db", driver="oracle.jdbc.driver.OracleDriver", jdbcurl="jdbc:oracle:thin:@//172.16.25.219:1521/orcl", username="baseline", password="baseline", readOnly="true", validationQuery="select 1 from dual";
    		DBUtil.startPool("db", driver, jdbcurl, username, password, readOnly, validationQuery);
    		tm.begin();
    		
    		dbutil.executeSelect("db","Select 1 from dual");
    		tm.commit();
    		System.out.println("dbutil.size():" + dbutil.size());
    		DBUtil.stopPool("db");
    		PreparedDBUtil db = new PreparedDBUtil();
    		db.preparedSelect("db","Select 1 from dual");
    		db.executePrepared();
    		
//    		dbutil.executeSelect("db","Select 1 from dual");
    		
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
	}
    @Test
    public void testDBStatusStatic() throws SQLException
    {
    	int numactive = DBUtil.getNumActive("mysql");
    	int numIdle = DBUtil.getNumIdle("mysql");
    	DBUtil.getConection("mysql");
    	List<PoolableConnection> objects = (List<PoolableConnection>)DBUtil.getTraceObjects("mysql");
    	for(int i = 0;  objects != null && i < objects.size(); i ++)
    	{
    		PoolableConnection con = objects.get(i);
    		System.out.println(con.getAutoCommit());
    		System.out.println(con.toString());
    	}
    	System.out.println();
//    	int numactive = DBUtil.getNumActive("bspf");
    	
    }
    @Test
    public void testStartPoolFromConf()
    {
    	String configfile = "custom_poolman.xml";
    	SQLUtil.startPoolFromConf(configfile);
    	DBUtil dbutil = new DBUtil();
    	try {
			dbutil.executeSelect("bspf_custom_1","Select * from tableinfo");
			System.out.println("bspf_custom_1:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			dbutil.executeSelect("bspf_custom","Select * from tableinfo");
			System.out.println("bspf_custom:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    @Test
    public void startPoolFromConf()
	{
    	String configfile = "custom_poolman.xml";
    	String dbnamespace = "test";
    	SQLUtil.startPoolFromConf(configfile,dbnamespace);
    	DBUtil dbutil = new DBUtil();
    	try {
			dbutil.executeSelect("test:bspf_custom_1","Select * from tableinfo");
			System.out.println("test:bspf_custom_1:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			dbutil.executeSelect("test:bspf_custom","Select * from tableinfo");
			System.out.println("test:bspf_custom:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			dbutil.stopPool("test:bspf_custom_1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			dbutil.stopPool("test:bspf_custom");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    @Test
	public void startPoolFromConfWithAllParams()
	{
    	String configfile = "custom_poolman.xml";
    	String dbnamespace = "test";
    	String[] dbnames = new String[]{"bspf_custom_1"};
    	SQLUtil.startPoolFromConf(configfile,dbnamespace,dbnames);
    	DBUtil dbutil = new DBUtil();
    	try {
			dbutil.executeSelect("test:bspf_custom_1","Select * from tableinfo");
			System.out.println("test:bspf_custom_1:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			dbutil.executeSelect("test:bspf_custom","Select * from tableinfo");
			System.out.println("test:bspf_custom:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Test
	public void startPoolFromConfNulldbnamespace() {
		String configfile = "custom_poolman.xml";
    	String dbnamespace = null;
    	String[] dbnames = new String[]{"bspf_custom_1"};
    	SQLUtil.startPoolFromConf(configfile,dbnamespace,dbnames);
    	DBUtil dbutil = new DBUtil();
    	try {
			dbutil.executeSelect("bspf_custom_1","Select * from tableinfo");
			System.out.println("bspf_custom_1:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			dbutil.executeSelect("bspf_custom","Select * from tableinfo");
			System.out.println("bspf_custom:"+dbutil.size());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void testStartPoolFromTempate() throws SQLException
	{
		DBUtil.getConection();
		String poolname = "bspf-custom";
		String driver = "org.apache.derby.jdbc.EmbeddedDriver";
		String jdbcurl = "jdbc:derby:D:/workspace/bbossgroups-3.1/bboss-mvc/database/cimdb";
		String username = ""; 
		String password = "";
		String readOnly = "false";
		String txIsolationLevel = "READ_COMMITTED";
		String validationQuery = "select 1 from dual";
		String jndiName = "jdbc/derby-ds-custom";
		int initialConnections = 2;
		int minimumSize = 0;
		int maximumSize = 10;
		boolean usepool = true;
		boolean  external = true;
		String externaljndiName = "jdbc/derby-ds";        
		boolean showsql = true;		
		SQLUtil.startPool( poolname, driver, jdbcurl, username, password,
        		 readOnly,
        		 txIsolationLevel,
        		 validationQuery,
        		 jndiName,   
        		 initialConnections,
        		 minimumSize,
        		 maximumSize,
        		 usepool,
        		  external,
        		 externaljndiName        , showsql		
        		);
	}
   发表时间:2011-06-29  
欢迎大家一起交流,呵呵
0 请登录后投票
   发表时间:2011-06-29  
custom_poolman.xml文件的内容:
<?xml version="1.0" encoding="gb2312"?>

<poolman>

  <management-mode>local</management-mode>

<datasource>

    <dbname>bspf_custom</dbname>
	<loadmetadata>false</loadmetadata>
    <jndiName>jdbc/mysql-ds</jndiName>
    <driver>com.mysql.jdbc.Driver</driver>

     <url>jdbc:mysql://172.16.25.139:3306/cim</url> 

    <username>root</username>
    <password>123456</password>

    <txIsolationLevel>READ_COMMITTED</txIsolationLevel>

    <nativeResults>true</nativeResults>

    <poolPreparedStatements>false</poolPreparedStatements>

    <initialConnections>2</initialConnections>
    
    <minimumSize>0</minimumSize>
    <maximumSize>10</maximumSize>
	<!--控制connection达到maximumSize是否允许再创建新的connection
		true:允许,缺省值
		false:不允许-->
    <maximumSoft>false</maximumSoft>
    
    <!-- 
    是否检测超时链接(事务超时链接)
    true-检测,如果检测到有事务超时的链接,系统将强制回收(释放)该链接
    false-不检测,默认值
     -->
    <removeAbandoned>true</removeAbandoned>
	<!--
		链接使用超时时间(事务超时时间)
		单位:秒
	-->
    <userTimeout>50</userTimeout>
    <!-- 
    	系统强制回收链接时,是否输出后台日志
    	true-输出,默认值
    	false-不输出
     -->
    <logAbandoned>true</logAbandoned>
    
    <!-- 
    	数据库会话是否是readonly,缺省为false
     -->
    <readOnly>false</readOnly>
	
	<!--
		对应属性:timeBetweenEvictionRunsMillis
		the amount of time (in milliseconds) to sleep between examining idle objects for eviction 
	-->
	<skimmerFrequency>10</skimmerFrequency>
	<!--对应于minEvictableIdleTimeMillis 属性:
	minEvictableIdleTimeMillis the minimum number of milliseconds 
	an object can sit idle in the pool before it is eligable for evcition
	单位:秒
	
	空闲链接回收时间,空闲时间超过指定的值时,将被回收
	-->
	<connectionTimeout>60</connectionTimeout>
	<!--
	numTestsPerEvictionRun 
	the number of idle objects to 
	examine per run within the idle object eviction thread (if any)
	
	每次回收的链接个数 
	-->
    <shrinkBy>5</shrinkBy>
    <!--
    /**
     * 检测空闲链接处理时,是否对空闲链接进行有效性检查控制开关
     * true-检查,都检查到有无效链接时,直接销毁无效链接
     * false-不检查,缺省值
     */
     -->
    <testWhileidle>true</testWhileidle>


    <!--
        定义数据库主键生成机制
        缺省的采用系统自带的主键生成机制,
        外步程序可以覆盖系统主键生成机制
        由值来决定
        auto:自动,一般在生产环境下采用该种模式,
               解决了单个应用并发访问数据库添加记录产生冲突的问题,效率高,如果生产环境下有多个应用并发访问同一数据库时,必须采用composite模式
        composite:结合自动和实时从数据库中获取最大的主键值两种方式来处理,开发环境下建议采用该种模式,
                   解决了多个应用同时访问数据库添加记录时产生冲突的问题,效率相对较低, 如果生产环境下有多个应用并发访问同一数据库时,必须采用composite模式
    -->
    <keygenerate>composite</keygenerate>

	<!--poolman的日志信息输出改用log4j来输出到日志文件,相关的配置见log4j.properties文件-->
    <!--<logFile>dbaccess.log</logFile>
    <debugging>true</debugging>-->
    <!-- 请求链接时等待时间,单位:秒
    客服端程序请求链接等待时间超过指定值时,后台包等待超时异常
     -->
    <maxWait>60</maxWait>
    
    <!-- 
    	链接有效性检查sql语句
     -->
    <validationQuery>select 1</validationQuery>
    
    <autoprimarykey>false</autoprimarykey>
	<showsql>false</showsql>

  </datasource>
  
  <datasource>

    <dbname>bspf_custom_1</dbname>
	<loadmetadata>false</loadmetadata>
    <jndiName>jdbc/mysql-ds-1</jndiName>
    <driver>com.mysql.jdbc.Driver</driver>

     <url>jdbc:mysql://172.16.25.139:3306/cim</url> 

    <username>root</username>
    <password>123456</password>

    <txIsolationLevel>READ_COMMITTED</txIsolationLevel>

    <nativeResults>true</nativeResults>

    <poolPreparedStatements>false</poolPreparedStatements>

    <initialConnections>2</initialConnections>
    
    <minimumSize>0</minimumSize>
    <maximumSize>10</maximumSize>
	<!--控制connection达到maximumSize是否允许再创建新的connection
		true:允许,缺省值
		false:不允许-->
    <maximumSoft>false</maximumSoft>
    
    <!-- 
    是否检测超时链接(事务超时链接)
    true-检测,如果检测到有事务超时的链接,系统将强制回收(释放)该链接
    false-不检测,默认值
     -->
    <removeAbandoned>true</removeAbandoned>
	<!--
		链接使用超时时间(事务超时时间)
		单位:秒
	-->
    <userTimeout>50</userTimeout>
    <!-- 
    	系统强制回收链接时,是否输出后台日志
    	true-输出,默认值
    	false-不输出
     -->
    <logAbandoned>true</logAbandoned>
    
    <!-- 
    	数据库会话是否是readonly,缺省为false
     -->
    <readOnly>false</readOnly>
	
	<!--
		对应属性:timeBetweenEvictionRunsMillis
		the amount of time (in milliseconds) to sleep between examining idle objects for eviction 
	-->
	<skimmerFrequency>10</skimmerFrequency>
	<!--对应于minEvictableIdleTimeMillis 属性:
	minEvictableIdleTimeMillis the minimum number of milliseconds 
	an object can sit idle in the pool before it is eligable for evcition
	单位:秒
	
	空闲链接回收时间,空闲时间超过指定的值时,将被回收
	-->
	<connectionTimeout>60</connectionTimeout>
	<!--
	numTestsPerEvictionRun 
	the number of idle objects to 
	examine per run within the idle object eviction thread (if any)
	
	每次回收的链接个数 
	-->
    <shrinkBy>5</shrinkBy>
    <!--
    /**
     * 检测空闲链接处理时,是否对空闲链接进行有效性检查控制开关
     * true-检查,都检查到有无效链接时,直接销毁无效链接
     * false-不检查,缺省值
     */
     -->
    <testWhileidle>true</testWhileidle>


    <!--
        定义数据库主键生成机制
        缺省的采用系统自带的主键生成机制,
        外步程序可以覆盖系统主键生成机制
        由值来决定
        auto:自动,一般在生产环境下采用该种模式,
               解决了单个应用并发访问数据库添加记录产生冲突的问题,效率高,如果生产环境下有多个应用并发访问同一数据库时,必须采用composite模式
        composite:结合自动和实时从数据库中获取最大的主键值两种方式来处理,开发环境下建议采用该种模式,
                   解决了多个应用同时访问数据库添加记录时产生冲突的问题,效率相对较低, 如果生产环境下有多个应用并发访问同一数据库时,必须采用composite模式
    -->
    <keygenerate>composite</keygenerate>

	<!--poolman的日志信息输出改用log4j来输出到日志文件,相关的配置见log4j.properties文件-->
    <!--<logFile>dbaccess.log</logFile>
    <debugging>true</debugging>-->
    <!-- 请求链接时等待时间,单位:秒
    客服端程序请求链接等待时间超过指定值时,后台包等待超时异常
     -->
    <maxWait>60</maxWait>
    
    <!-- 
    	链接有效性检查sql语句
     -->
    <validationQuery>select 1</validationQuery>
    
    <autoprimarykey>false</autoprimarykey>
	<showsql>false</showsql>

  </datasource>
  
  <datasource external="true">

    <dbname>mq</dbname>
    <externaljndiName>jdbc/mysql-ds</externaljndiName>
	<showsql>false</showsql>

  </datasource>
  
 <datasource external="true">

    <dbname>kettle</dbname>
    <externaljndiName>jdbc/mysql-ds</externaljndiName>
	<showsql>false</showsql>

 </datasource>
  


</poolman>
0 请登录后投票
   发表时间:2011-07-04  
通过以下一组接口你可以非常方便地动态创建和管理连接池,包括启动,停止,状态检测,可以根据需要调用相应的启动和创建方法,呵呵
DBUtil.stopPool
DBUtil.startPool
DBUtil.statusCheck
DBUtil.startPool("db", driver, jdbcurl, username, password, readOnly, validationQuery);   
SQLUtil.startPoolFromConf(configfile);   
SQLUtil.startPoolFromConf(configfile,dbnamespace);   
SQLUtil.startPoolFromConf(configfile,dbnamespace,dbnames);  
SQLUtil.startPool( poolname, driver, jdbcurl, username, password,   
                 readOnly,   
                 txIsolationLevel,   
                 validationQuery,   
                 jndiName,      
                 initialConnections,   
                 minimumSize,   
                 maximumSize,   
                 usepool,   
                  external,   
                 externaljndiName        , showsql         
                );  
0 请登录后投票
   发表时间:2011-07-09  
bbossgroups项目新域名开通:
http://www.bbossgroups.com
0 请登录后投票
   发表时间:2011-07-20  
持久层的代码那里有下载或者jar包也可以啊
0 请登录后投票
   发表时间:2011-07-20  
379548695 写道
持久层的代码那里有下载或者jar包也可以啊

http://sourceforge.net/projects/bboss/files/
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics