zoukankan      html  css  js  c++  java
  • 数据库连接池

    1.自定义数据库连接池

    public class MyPool {
        private int init_count = 3;
        private int max_count = 6;
        private int curr_count = 0;
        private LinkedList<Connection> pool = new LinkedList<Connection>();
    
        public MyPool(){
            for(int i = 0 ;i < init_count ;i++)
            {
                curr_count++;
                pool.addLast(createConnection());
            }
        }
    
        /**
         * 使用代理类,每次调用connection的close方法,都把连接放入连接池中
         */
        private Connection createConnection(){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection connection = DriverManager.getConnection("jdbc:mysql:///test", "root", "juaner767");
                Connection proxy = (Connection)Proxy.newProxyInstance(
                        connection.getClass().getClassLoader(),//类加载器
    //                    connection.getClass().getInterfaces() 实现的接口,对象是一个具体的类时这样使用
                        new Class[]{Connection.class}, //connection是接口,所以要这样使用
                        new InvocationHandler() {
                            //当调用connection对象方法的时候,会自动触发事务处理器
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                String name = method.getName();
                                Object result= null;
                                //当执行close方法时,把连接放入连接池
                                if("close".equals(name))
                                {
                                    System.out.println("调用对象被监测的接口");
                                    releaseConnection(connection);
                                }else{
                                    result = method.invoke(connection, args);
                                }
                                return result;
                            }
                        }
                );
                return proxy;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        public Connection getConnection(){
            Connection connection = null;
            if(pool.size() > 0){
                connection = pool.removeFirst();
            }else{
                if(curr_count < max_count){
                    curr_count++;
                    connection = createConnection();
                }else {
                    throw new RuntimeException("当前已经达到最大连接数,无法获取连接!");
                }
            }
            return connection;
        }
    
        public void releaseConnection(Connection connection){
            if(connection == null)
                return;
            if(pool.size() < init_count)
                pool.addLast(connection);
            else{
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                curr_count--;
            }
        }
    }

    2.dbcp连接池组件

      DBCP 是 Apache 软件基金组织下的开源连接池实现。使用DBCP数据源,应用程序应在系统中增加如下两个 jar 文件:
        Commons-dbcp.jar:连接池的实现
        Commons-pool.jar:连接池实现的依赖库
      Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。

      db.properties:

    url=jdbc:mysql:///student
    driverClassName=com.mysql.jdbc.Driver
    username=root
    password=juaner767
    initialSize=3
    maxActive=6
    maxIdle=3000

      使用dbcp连接池:

       @Test
        public void test2() throws Exception {
            //加载配置文件
            Properties prop = new Properties();
            InputStream in = Demo1.class.getResourceAsStream("db.properties");
            prop.load(in);
    DataSource dataSource
    = BasicDataSourceFactory.createDataSource(prop); Connection connection = dataSource.getConnection(); connection.prepareStatement("DELETE from student_info WHERE stuId = 2008006").executeUpdate(); connection.close(); }

    3.c3p0连接池组件

      C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。

      在src下设置配置文件c3p0-config.xml:

    <c3p0-config>
      <default-config>
         <property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
         <property name="driverClass">com.mysql.jdbc.Driver</property>
         <property name="user">root</property>
         <property name="password">juaner767</property>
         <property name="initialPoolSize">3</property>
         <property name="maxPoolSize">6</property>
         <property name="maxIdleTime">1000</property>
      </default-config>
    </c3p0-config>

      使用c3p0连接池:

        @Test
        public void test2()throws Exception{
            //自动加载src下的c3p0的配置文件c3p0-config.xml
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            Connection connection = dataSource.getConnection();
            PreparedStatement preparedStatement  = null;
            String sql ="INSERT INTO student_info (stuName,telephone) VALUES(?,?) ";
            preparedStatement = connection.prepareStatement(sql);
            for(int i = 0;i<10;i++) {
                preparedStatement.setString(1,"测试"+i);
                preparedStatement.setInt(2,1353356234);
                preparedStatement.executeUpdate();
            }
            connection.close();
        }

    4.区别

    dbcp没有自动回收空闲连接的功能。
    c3p0有自动回收空闲连接功能。

    5.在hibernate中使用c3p0连接池

      在hibernate.cfg.xml中配置:

            <!--连接池配置-->
            <!--连接池管理类、驱动管理类-->
            <property name="hibernate.connection.provider_class">
                org.hibernate.connection.C3P0ConnectionProvider
            </property>
            <!--配置连接池参数信息-->
            <property name="hibernate.c3p0.min_size">2</property>
            <property name="hibernate.c3p0.max_size">4</property>
            <property name="hibernate.c3p0.timeout">5000</property>
            <property name="hibernate.c3p0.max_statements">10</property>
            <property name="hibernate.c3p0.idle_test_period">30000</property>
            <property name="hibernate.c3p0.acquire_increment">2</property>
     
  • 相关阅读:
    HDU_oj_2048 错排问题
    HDU_oj_2047 阿牛的EOF牛肉面
    HDU_oj_2046 骨牌铺方格
    HDU_oj_2045 不容易系列之RPG问题
    拷贝构造函数(三)——重载赋值运算符
    拷贝构造函数(二)——深拷贝与浅拷贝
    拷贝构造函数(一)——哲学三连
    HDU_oj_2044 一只小蜜蜂
    【转发】【linux】【ftp】CentOS 7.0安装配置Vsftp服务器
    【编码】【转发】enca 转换编码
  • 原文地址:https://www.cnblogs.com/juaner767/p/5575713.html
Copyright © 2011-2022 走看看