Database connection pool (1) Self-built connection pool

Introduction

Previously, every time the database was added, deleted, modified, and checked, a Connection link was first established, and then closed after use. If thousands of users add and modify data, it would be a waste of performance and development time. In fact, a Connection can be used to link and close, which can be achieved through a connection pool.

connection pool

Use the collection to save multiple links, and directly take out the links from the link pool for subsequent use, without the need to recreate them, saving time.

create

//创建一个集合,这个集合里面用来存放Connection;
	private static ArrayList<Connection> conList = new ArrayList<Connection>();
    //在整个服务器启动的时候,就直接先把链接资源创建起来,这样就不用每次使用的时候再去创建
	static {
    
    
		for(int i =0;i<=5;i++) {
    
    
			//通过遍历,在类的加载中先在连接池中创建了5个连接
			Connection con = createConnection();
			conList.add(con);
		}
		
	}
	//自动获取链接的方法
	public static Connection getConnection() {
    
    
		//在静态代码块中定义了5个链接,使用的时候,如果静态代码块中有链接,则使用。
		//如果静态代码块中的链接已经用完,则可以使用createConnection方法创建新的链接。
		if(conList.isEmpty()==false) {
    
    
			Connection con = conList.get(0);
			conList.remove(con);
			return con;
		}else {
    
    
			return createConnection();
		}
	}
	// 建立数据库连接
	public static Connection createConnection() {
    
    

		try {
    
    
			Class.forName("com.mysql.cj.jdbc.Driver");

			return DriverManager.createConnection(connectionUrl, "root", "121156");
		} catch (Exception e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

perfect

After the links in the link pool are used, they need to be returned. You only need to change the previously encapsulated closeConnection() method, and there is no need to close the connection pool.

private static void closeConnection(Connection con) {
    
    
//未使用链接池时释放资源
//		try {
    
    
//			if (con != null)
//				con.close();
//		} catch (SQLException e) {
    
    
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//归还链接池
		conList.add(con);
	}

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/107145749