如何使用jndi设置连接超时?

时间:2015-09-29 11:24:59

标签: java sql jndi connection-pooling

我有这段代码:

Object objc = null;

if (jdbcFactory == null) {
  try {
    InitialContext c = new InitialContext();
    this.jdbcFactory = (DataSource) c.lookup(this.jndiName);

  }
  catch (Exception e) {
    Logger log = Logger.getLogger(this.getClass());

  }
}
// jdbcFactory initiated.
try {
  objc = this.jdbcFactory.getConnection();  
} catch (Exception e) {

}
return objc;
}

如何设置连接超时? (不使用context.xml)

1 个答案:

答案 0 :(得分:0)

根据您的代码,您将this.jdbcFactory投射到javax.sql.DataSource;根据代码,此接口扩展javax.sql.CommonDataSource,定义了以下方法javax.sql.CommonDataSource#setLoginTimeout

此方法文档说明了:

 * <p>Sets the maximum time in seconds that this data source will wait
 * while attempting to connect to a database.  A value of zero
 * specifies that the timeout is the default system timeout
 * if there is one; otherwise, it specifies that there is no timeout.
 * When a <code>DataSource</code> object is created, the login timeout is
 * initially zero.