通信链路故障:如何从池中杀死死连接?

时间:2013-11-21 13:57:44

标签: mysql eclipse java-ee connection-pooling

我面临以下异常:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.io.EOFException.

为数据源指定以下池属性后,能够在连接超时时自动重新连接;但是池中存在的死连接正在被重用而不被杀死/驱逐(即验证查询和驱逐参数不起作用)。以下是我的代码。任何人都可以建议一些解决方案如何处理这个?

public class DbConnection {

  static DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();

  public static Connection getConnection() {

    PoolProperties p = new PoolProperties();

    p.setUrl("jdbc:mysql://192.168.0.9:3306/oet_v3?autoReconnect=true");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("napster123");
    p.setJmxEnabled(true);
    p.setTestWhileIdle(true);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(true);
    p.setValidationInterval(20000);
    p.setTimeBetweenEvictionRunsMillis(3000);
    p.setMaxActive(100);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setMinEvictableIdleTimeMillis(3000);
    p.setMinIdle(10);
    Connection con = null;

    try {
      Context ctx = new InitialContext();
      ((DataSourceProxy) datasource).setPoolProperties(p);

      con = datasource.getConnection();
      Statement st1 = con.createStatement();
      ResultSet rs1 = st1.executeQuery("select * from User_Login limit 0,1");
      if (rs1.next()) {
        System.out.println("LIVE CONNECTION********con: " + con + " rs.next=" + rs1.next());
      } else {
        System.out.println("&&&&&rs is null so secnd conn: " + con);
        DataSource datasource1 = new org.apache.tomcat.jdbc.pool.DataSource();
        ((DataSourceProxy) datasource1).setPoolProperties(p);
        con = datasource1.getConnection();
        return con;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (NamingException e) {
      e.printStackTrace();
    } finally {
      return con;
    }
    finally {
          System.out.println("before returning con: "+con);
       if (con!=null) try {return con;}catch (Exception ignore) {}
          return con;
       }
  }

}

0 个答案:

没有答案