Simple MySQL connection pool, supporting high concurrency.

Here is the programming house jb51 CC collects and arranges code fragments through the network.

Programming house Xiaobian now shares it with you and gives you a reference.

/**
 * 连接池类
 */
package com.junones.test;

import java.sql.Connection;
import java.sql.sqlException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.MysqL.jdbc.jdbc2.optional.MysqLDataSource;

public class MysqLPool {
    private static volatile MysqLPool pool;
    private MysqLDataSource ds;
    private Map<Connection,Boolean> map;
 
    private String url = "jdbc:MysqL://localhost:3306/test";
    private String username = "root";
    private String password = "root1234";
    private int initPoolSize = 10;
    private int maxPoolSize = 200;
    private int waitTime = 100;
    
    private MysqLPool() {
    	init();
    }
    
    public static MysqLPool getInstance() {
        if (pool == null) {
        	synchronized (MysqLPool.class) {
        		if(pool == null) {
	        		pool = new MysqLPool();
        		}
			}
        }
        return pool;
    }
    
    private void init() {
    	try {
    		ds = new MysqLDataSource();
            ds.setUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            ds.setCacheCallableStmts(true);
            ds.setConnectTimeout(1000);
            ds.setLoginTimeout(2000);
            ds.setUseUnicode(true);
            ds.setEncoding("UTF-8");
            ds.setZeroDateTimeBehavior("convertToNull");
            ds.setMaxReconnects(5);
            ds.setAutoReconnect(true);
            map = new HashMap<Connection,Boolean>();
            for (int i = 0; i < initPoolSize; i++) {
                map.put(getNewConnection(),true);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public Connection getNewConnection() {
        try {
            return ds.getConnection();
        } catch (sqlException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public synchronized Connection getConnection() {
        Connection conn = null;
        try {
            for (Entry<Connection,Boolean> entry : map.entrySet()) {
                if (entry.getValue()) {
                    conn = entry.getKey();
                    map.put(conn,false);
                    break;
                }
            }
            if (conn == null) {
                if (map.size() < maxPoolSize) {
                    conn = getNewConnection();
                    map.put(conn,false);
                } else {
                    wait(waitTime);
                    conn = getConnection();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    public void releaseConnection(Connection conn) {
        if (conn == null) {
            return;
        }
        try {
            if(map.containsKey(conn)) {
                if (conn.isClosed()) {
                    map.remove(conn);
                } else {
                    if(!conn.getAutoCommit()) {
                        conn.setAutoCommit(true);
                    }
                    map.put(conn,true);
                }
            } else {
                conn.close();
            }
        } catch (sqlException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 测试类
 */
package com.junones.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.sql.Statement;

public class TestMysqLPool {
	private static volatile int a;

	private synchronized static void incr() {
		a++;
	}

	public static void main(String[] args) throws InterruptedException {
		int times = 10000;
		long start = System.currentTimeMillis();
		for (int i = 0; i < times; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {

					MysqLPool pool = MysqLPool.getInstance();
					Connection conn = pool.getConnection();
					Statement stmt = null;
					ResultSet rs = null;
					try {
						stmt = conn.createStatement();
						rs = stmt.executeQuery("select id,name from t_test");
						while (rs.next()) {
							System.out.println(rs.getInt(1) + ","
									+ rs.getString(2));
						}
					} catch (sqlException e) {
						e.printStackTrace();
					} finally {
						incr();
						if (rs != null) {
							try {
								rs.close();
							} catch (sqlException e) {
								e.printStackTrace();
							}
						}
						if (stmt != null) {
							try {
								stmt.close();
							} catch (sqlException e) {
							}
						}
						pool.releaseConnection(conn);
					}
				}
			}).start();
		}
		while (true) {
			if (a == times) {
				System.out.println("finished,time:"
						+ (System.currentTimeMillis() - start));
				break;
			}
			Thread.sleep(100);
		}
	}
}

测试结果: 1万个并发, 5秒完成。

The above is all the code content collected by the programming home (jb51. CC). I hope this article can help you solve the program development problems you encounter.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>