与自动重新连接的JDBC连接

bum*_*box 11 java firebird jdbc jaybird

我正在使用JDBC连接到数据库服务器.连接是通过无线网络进行的,有时可能很狡猾.在连接丢失的那一刻,我需要关闭并重新启动应用程序.

有没有人有一些代码示例,我可以编写某种包装器来自动重新连接并重新运行最后一个查询?这样可以省去很多麻烦.

我只是不确定它应该如何/可以实施.也许已经有了可用的东西?

zka*_*hik 6

即使您使用JDBC连接池提供的应用程序服务器或apache commons池,也值得编写重试逻辑.根据应用程序服务器的配置,应用程序服务器将清除所有池连接并重新创建一组新连接.这是一个示例:

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//
// How many times do you want to retry the transaction
// (or at least _getting_ a connection)?
//
int retryCount = 5;
boolean transactionCompleted = false;
do {

  try {
    conn = getConnection(); // assume getting this from a
    // javax.sql.DataSource, or the
    // java.sql.DriverManager

    retryCount = 0;
    stmt = conn.createStatement();
    String query = "Some sample SQL";
    rs = stmt.executeQuery(query);
    while (rs.next()) {
    }
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;

    conn.close();
    conn = null;
    transactionCompleted = true;
  } catch (SQLException sqlEx) {
    //
    // The two SQL states that are 'retry-able' 
    // for a communications error.
    //
    // Only retry if the error was due to a stale connection,
    // communications problem 
    //
    String sqlState = sqlEx.getSQLState();
    if ("Substitute with Your DB documented sqlstate number for stale connection".equals(sqlState) ) {
      retryCount--;
    } else {
      retryCount = 0;
    }
  } finally {
    if (rs != null) {
      try {
        rs.close();
      } catch (SQLException sqlEx) {
        // log this
      }
    }
    if (stmt != null) {
      try {
        stmt.close();
      } catch (SQLException sqlEx) {
        // log this
      }
    }
    if (conn != null) {
      try {
        //
        // If we got here, and conn is not null, the
        // transaction should be rolled back, as not
        // all work has been done
        try {
          conn.rollback();
        } finally {

          conn.close();
        }
      } catch (SQLException sqlEx) {
        //
        // If we got an exception here, something
        // pretty serious is going on, so we better
        // pass it up the stack, rather than just
        // logging it. . .
        throw sqlEx;
      }
    }
  }
} while (!transactionCompleted && (retryCount > 0));
Run Code Online (Sandbox Code Playgroud)


Pas*_*ent 3

让连接池为您处理这个问题,其中许多可以验证连接。DBCP也是如此,它有一个testOnBorrow参数,强制在使用每个连接之前对其进行健全性检查。该参数的默认值为true,只需validationQuery将其设置为非空字符串即可生效。所以设置好validationQuery就可以了!查看文档