数据库连接池代码实现 待我称王封你为后i 2022-03-18 12:09 177阅读 0赞 # 数据库连接池代码实现 # ## 步骤 ## 大体步骤和之前封装JDBC差不多,不懂的可以去看看上一篇blog。 所以今天我简单描述一下。 1. 在src目录创建一个配置文件db.properties DRIVER:com.mysql.jdbc.Driver URL:jdbc:mysql://localhost:3306/db214 USER:root PASSWORD:123456 1. 连接池createConnection方法(创建连接) private static InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); static{ try { properties.load(is); //配置文件加载 jdbcDriver=properties.getProperty("DRIVER"); //获取驱动 jdbcurl=properties.getProperty("URL"); //获取URL userName=properties.getProperty("USER"); //获取用户名 password=properties.getProperty("PASSWORD"); //获取密码 Class.forName(jdbcDriver); //加载驱动 is.close(); //关闭输入流 } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } //获取数据库链接 private static Connection createConnection(){ //定义方法获取数据库链接 Connection conn=null; try { conn = DriverManager.getConnection(jdbcurl, userName, password); //获取数据库链接 } catch (SQLException e) { e.printStackTrace(); } return conn; } 1. getConnection方法 public synchronized static Connection getConnection() throws Exception{ Connection conn=null; //数据库链接 if(pool==null){ //判断连接池是否已被初始化 pool=new ArrayList<>(); //如果为null则直接初始化 } if(pool.isEmpty()){ conn=createConnection(); //如果连接池为空,则直接创建 }else{ conn = (Connection) pool.get(pool.size()-1); //如果连接池中有链接元素则从连接池获取最后一个元素 pool.remove(pool.size()-1); //当获取到连接池最后一个元素后则在连接池中移除最后一个元素 } return conn; //返回connection对象 } 1. closeConnection方法 public synchronized static void closeConnection(Connection conn) { if (conn!=null) { //判断链接是否为空 if(pool.size()>=POOL_MAX_SIZE){ //判断连接池大小是否达到最大连接数 try { conn.close(); //关闭链接 } catch (SQLException e) { e.printStackTrace(); } }else { pool.add(conn); //如果没有达到最大连接数,则将链接归还连接池 } } } 1. initPool方法 public static void initPool() throws Exception{ if(pool==null){ pool=new ArrayList<>(); while(pool.size()<POOL_MIN_SIZE){ pool.add(DBConnPool.createConnection()); } } } 1. Main方法 public static void main(String[] args) { Connection con = null; //定义一个空连接 try { initPool(); //初始化连接池 long stattime=System.currentTimeMillis(); con = getConnection(); //从连接池里获取链接 long endtime=System.currentTimeMillis(); int rs=(int) (endtime-stattime); //获取总共耗时多久 System.out.println("从连接池中获取链接耗时:"+rs+"\t"+stattime+"\t"+endtime); long stime=System.currentTimeMillis(); Connection conn =DriverManager.getConnection(jdbcurl, userName, password); long etime=System.currentTimeMillis(); System.out.println("不用连接池创建链接耗时:"+(etime-stime)+"\t"+stime+"\t"+etime); closeConnection(con); //归还链接 } catch (Exception e) { e.printStackTrace(); } System.out.println(con); } }
还没有评论,来说两句吧...