JDBC+c3p0连接池的使用

 
package com.hd.xy.jdbc;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;


/**
 * 获取数据源文件信息,建立连接池,获取连接
 */
public class GetDb extends Thread {
    private static Properties prop = new Properties();
    public static String url ="";
    public static String username = "";
    public static String password = "";


    private static final GetDb instance = new GetDb();//重写的构造方法(获取配置文件)赋值给构造的对象
    private static ComboPooledDataSource comboPooledDataSource;
    private static ComboPooledDataSource comboPooledDataSource1;
    private static DruidDataSource druidDataSource;


    static {
        try {
            GetDb db=getInstance();
            url=db.getProperty("test3-datasource.url");
            username=db.getProperty("test3-datasource.username");
            password=db.getProperty("test3-datasource.password");


            if(null==comboPooledDataSource){
                comboPooledDataSource = new ComboPooledDataSource();
            }
            comboPooledDataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
            comboPooledDataSource.setJdbcUrl(url);
            comboPooledDataSource.setUser(username);
            comboPooledDataSource.setPassword(password);
            //下面是设置连接池的一配置:连接池1
            comboPooledDataSource.setMaxPoolSize(150);
            comboPooledDataSource.setInitialPoolSize(120);
            comboPooledDataSource.setMinPoolSize(120);    //最小连接数量,据测试此数量为 连接被释放后的最大空闲连接数
            comboPooledDataSource.setMaxIdleTime(10);     //最大空闲时间,1秒内未使用则连接被释放。若为0则永不释放。Default: 0
            comboPooledDataSource.setIdleConnectionTestPeriod(15);//多长时间检查一次空闲连接,加快释放连接
            comboPooledDataSource.setUnreturnedConnectionTimeout(20);//MaxIdleTime的指定时间连接未kill则由连接缓冲池kill
            comboPooledDataSource.setAcquireIncrement(1);//当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3
            comboPooledDataSource.setAutoCommitOnClose(false);//连接关闭时默认将所有未提交的操作回滚。Default: false
            comboPooledDataSource.setBreakAfterAcquireFailure(false);//获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。Default: false
            comboPooledDataSource.setMaxStatements(0);    //JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
            comboPooledDataSource.setMaxStatementsPerConnection(0);//定义单个连接的Statements最大缓存数
            comboPooledDataSource.setNumHelperThreads(2); //c3p0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能通过多线程实现多个操作同时被执行。Default: 3
            //comboPooledDataSource.setCheckoutTimeout(18000); //当连接池用完时客户端调用getConnection()后等待获取新连接的时间
            comboPooledDataSource.setAcquireRetryAttempts(10);//--定义在从数据库获取新连接失败后重复尝试的次数:10,默认30




            //下面是设置连接池的一配置:连接池2
            if(null==druidDataSource){
                druidDataSource = new DruidDataSource();
            }
            druidDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            //下面是设置连接池的一配置
            druidDataSource.setMaxActive(100);  //可同时连接的最大的连接数
            druidDataSource.setMaxIdle(5);
            druidDataSource.setInitialSize(20);
            druidDataSource.setMinIdle(1);             //最小的空闲的连接数,低于这个数量会被创建新的连接
            druidDataSource.setMaxWait(300000);        //获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,
            druidDataSource.setTimeBetweenEvictionRunsMillis(5000);//配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
            druidDataSource.setTestWhileIdle(true);            //空闲时是否进行验证,检查对象是否有效
            druidDataSource.setMaxOpenPreparedStatements(0); //要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
            druidDataSource.setPoolPreparedStatements(false);//是否缓存Statements
            druidDataSource.setRemoveAbandonedTimeout(5);//超过时间限制,回收没有用(废弃)的连接(默认为 300秒,调整为180)
            druidDataSource.setRemoveAbandoned(true);//超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收


        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public synchronized Connection getConnection() {


            try{
                if(comboPooledDataSource.getNumIdleConnections()==0){
                    System.out.println("jdbc--连接已不足,请等待 切换连接池中........................................");
                    Connection connection=druidDataSource.getConnection();
                    if(null!=connection){
                        System.out.println("jdbc--切换连接池成功!........................................");
                        return connection;
                    }else{
                        connection.close();
                        wait(1000);
                    }
                }
                else{
                    System.out.println("jdbc--使用一个连接,连接池空闲连接数---" + comboPooledDataSource.getNumIdleConnections());
                    return comboPooledDataSource.getConnection();
                }
            }catch (SQLException e) {
                e.printStackTrace();
                System.out.println("jdbc--获取连接失败-------------------------------------------------SQLException");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            System.out.println("jdbc--线程被唤醒!获取连接中 -------------------------------------------------");
            return this.getConnection();
    }


    //加载配置文件
    private GetDb() {
        try{
            InputStream in = this.getClass().getResourceAsStream("/application.properties");
            prop.load(in);
            in.close();//关闭流
        }catch(Exception E){
            E.printStackTrace();
        }
    }




    public static GetDb getInstance() {
        return instance;
    }




    /*
     * 读属性对象prop读对应的健值
     */
    public String getProperty(String key){
        return (String) prop.get(key);
    }

}
package com.hd.xy.jdbc;
import org.apache.tomcat.jdbc.pool.DataSource;import org.springframework.core.env.Environment;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * jdbc 公共方法 */public class BaseDao{ private Environment environment; public BaseDao(){} //获取数据库连接 public Connection getConn(){ try { Connection conn = GetDb.getInstance().getConnection(); //Connection connection = GetDb.connection; return conn; }catch (Exception e){ e.printStackTrace(); } return null; } //查询结果 public JdbcQuery query(String sql,Object[] objs){ try { Connection con=null; con=getConn(); //System.out.println("query---"+sql); PreparedStatement prep=con.prepareStatement(sql); for(int i=0;i<objs.length;i++){ prep.setObject(i+1,objs[i]); } ResultSet rs=prep.executeQuery(); JdbcQuery jq=new JdbcQuery(); jq.setPre(prep); jq.setRs(rs); jq.setCon(con); return jq; } catch (SQLException e) { e.printStackTrace(); } return null; } //修改 public int update(String sql,Object[] objs){ try { Connection con=getConn(); PreparedStatement prep=con.prepareStatement(sql); for(int i=0;i<objs.length;i++){ System.out.println("objs["+i+"]---"+objs[i]); prep.setObject(i+1,objs[i]); } int i=prep.executeUpdate(); prep.close(); con.close(); System.out.println(i+"###################################="); return i; } catch (SQLException e) { e.printStackTrace(); } return -1; } //修改方法2--直接拼接sql执行 public int update(String sql){ try { Connection con=getConn(); PreparedStatement prep=con.prepareStatement(sql); int i=prep.executeUpdate(); prep.close(); con.close(); System.out.println(i+"###################################="); return i; } catch (SQLException e) { e.printStackTrace(); } return -1; } //新增 public int insert(String sql,Object[] objs){ try { Connection con=getConn(); PreparedStatement prep=con.prepareStatement(sql); for(int i=0;i<objs.length;i++){ //System.out.println("insert-objs["+i+"]---"+objs[i]); prep.setObject(i+1,objs[i]); } int i=prep.executeUpdate(); prep.close(); con.close(); return i; } catch (SQLException e) { e.printStackTrace(); } return -1; }}
 
/**
 * jdbc查询方法 工具类,返回此对象后,在每次使用完连接后手动释放连接
 */
 
package com.hd.xy.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JdbcQuery {
    public Connection con;
    public PreparedStatement pre;
    public ResultSet rs;

    public JdbcQuery(){}

    public PreparedStatement getPre() {
        return pre;
    }

    public void setPre(PreparedStatement pre) {
        this.pre = pre;
    }

    public ResultSet getRs() {
        return rs;
    }

    public void setRs(ResultSet rs) {
        this.rs = rs;
    }

    public Connection getCon() {
        return con;
    }

    public void setCon(Connection con) {
        this.con = con;
    }
}
 
//释放连接示例 
 
@Scheduled(fixedDelay = Five_Minute)
@RequestMapping(value = "/addPreServiceToTransAndItemGuide")
public void addPerServiceToTrans(){
      
            JdbcQuery jq=transDao.findByCondition(" WHERE ID='"+preServiceEntity.getUnid()+"'");
            ResultSet tresult=jq.getRs();
            int i=0;
            while(tresult.next()){
               ...;
            }
            tresult.close();
            jq.getPre().close();
            jq.getCon().close();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值