package com.nms.server.util;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;


public class BoneCPTest {

	public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		BoneCPConfig config = new BoneCPConfig();
		
		config.setJdbcUrl("jdbc:oracle:thin:@10.0.6.100:1521:ict");
		config.setUsername("nms");
		config.setPassword("nms");
		
		config.setPartitionCount(1);				// 设置分区个数：1
		config.setMaxConnectionsPerPartition(1);	// 设置最大连接数：5
		config.setLazyInit(true);					// 连接池初始化默认为空，最小连接数失效
		config.setMinConnectionsPerPartition(1);
		config.setAcquireIncrement(1);	// 设置每次增长的连接数：1
		
		config.setLogStatementsEnabled(true);	// 打印SQL
		
		config.setAcquireRetryDelay(2, TimeUnit.SECONDS);	// 20s
		config.setAcquireRetryAttempts(3);					// 3 times
//		config.setConnectionTimeout(10, TimeUnit.SECONDS);	// 超时时间
//		config.setMaxConnectionAge(120, TimeUnit.SECONDS);
//		config.setInitSQL("select 1 from dual");
		
		config.setConnectionTestStatement("select 1234567 from dual");
		config.setIdleConnectionTestPeriod(1, TimeUnit.MINUTES);
		
		BoneCP bonecpPool = new BoneCP(config);
		
		System.out.println(config.getConnectionTestStatement());
		System.out.println(config.getIdleConnectionTestPeriodInMinutes());
		
		boolean repeatFlag = true;
		boolean resetDB = false;
		while(repeatFlag) {
			Date d = new Date();
			System.out.println(d+"新连接开始");
			try{ 
				Connection conn = bonecpPool.getConnection();
				System.out.println(d+" "+conn);
				// 显示连接池连接个数
				System.out.println(d+"创建连接" + bonecpPool.getTotalCreatedConnections() + "个，已使用"
						+ bonecpPool.getTotalLeased() + "个，未占用" + bonecpPool.getTotalFree() + "个");
//				boolean isvalid = conn.isValid(0);
				boolean isvalid = true;
				System.out.println(d+"\t" + isvalid);
				if(isvalid) {
					conn.prepareStatement("select * from dual").executeQuery();
				}
//				conn.close();
			} catch (Exception e) {
				System.out.println(d+"start*****************************************");
				e.printStackTrace();
				resetDB = true;
				System.out.println(d+"[end]*****************************************");
			}
			System.out.println(d+"当前连接结束\n----------\n\n");
			Thread.sleep(5000);
		}
	}
}
