BoneCP 0.7.1 学习一

 

数据连接池的简单配置,连接申请,连接释放过程,连接申请超时

如下:

package com.zjf.test.bonecp;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class App {
	
	private final static String DRIVER = "com.mysql.jdbc.Driver";

	static{
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws SQLException {
		BoneCPConfig config = new BoneCPConfig();
		config.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test_dbutil?characterEncoding=utf-8");
		config.setUsername("root"); 
		config.setPassword("");
		config.setConnectionTimeout(3l, TimeUnit.SECONDS);
		config.setMinConnectionsPerPartition(5);
		config.setMaxConnectionsPerPartition(100);
		config.setPartitionCount(1);
		
		final BoneCP pool = new BoneCP(config);
		final List<Connection> list = new ArrayList<Connection>();
		
		System.out.println("start");
		
		new Thread(new Runnable(){
			public void run() {
				try {
					int i=1;
					while(true){
						Connection conn = pool.getConnection();
						list.add(conn);
						
						Thread.sleep(1000);
						
						System.out.println(pool.getTotalCreatedConnections());
						System.out.println(pool.getTotalFree());
						System.out.println(pool.getTotalLeased());
						System.out.println("========================= i=" + i++);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		new Thread(new Runnable(){
			public void run() {
				try {
					Thread.sleep(10000);
					while(true){
						
						Thread.sleep(500);
						if(list.size() > 0){
							Connection conn = list.remove(0);
							try{
								if(conn != null){
									conn.close();
									conn = null;
								}
							}finally{}
						} else {
							break;
						}
						
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		System.out.println("end");
	}
}

你可能感兴趣的:(BoneCP 0.7.1 学习一)