本文向大家介绍了简单的MySQL连接池,用于App服务端比较合适,分享给大家供大家参考,具体内容如下

/**
 * 连接池类
 */
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秒完成。

以上就是为大家分享的MySQL连接池类,希望大家喜欢,谢谢大家的关注。

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。