加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql使用jdbc时,需要关注的事情

发布时间:2020-12-13 17:05:49 所属栏目:百科 来源:网络整理
导读:超时时间问题 这个现场环境遇到过,程序一直处于等待状态,大致是因为没有设置超时时间,默认是0,0表示,超时不限制,这样有可能会出现获取链接时一直处于等待状态。 使用jdbc一般使用java.sql.DriverManager.getConnection方法 public static Connection g

超时时间问题

这个现场环境遇到过,程序一直处于等待状态,大致是因为没有设置超时时间,默认是0,0表示,超时不限制,这样有可能会出现获取链接时一直处于等待状态。

使用jdbc一般使用java.sql.DriverManager.getConnection方法

public static Connection getConnection(String url,
String user,String password)

这里会有个调用如下代码的地方。

Connection con = aDriver.driver.connect(url,info);

这里大致是会根据相应的driver调用相应的获取链接方法。

比如postgresql的

看了下postgresql-9.0-801.jdbc4.jar中的源文件。

其中有如下代码

Driver中的connect方法

public Connection connect(String url,Properties info)
throws SQLException
{
Properties defaults;
try
{
defaults = getDefaultProperties();
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Error loading default settings from driverconfig.properties"),PSQLState.UNEXPECTED_ERROR,ioe);
}

Properties props = new Properties(defaults);
for (Enumeration e = info.propertyNames(); e.hasMoreElements(); )
{
String propName = (String)e.nextElement();
props.setProperty(propName,info.getProperty(propName));
}

if ((props = parseURL(url,props)) == null)
{
logger.debug("Error in url: " + url);
return null;
}
try
{
logger.debug("Connecting with URL: " + url);

long timeout = timeout(props);
if (timeout <= -3913251033890947072L)
return makeConnection(url,props);

ConnectThread ct = new ConnectThread(url,props);
new Thread(ct,"PostgreSQL JDBC driver connection thread").start();
return ct.getResult(timeout);
}

我们这里只需要关注timeout关键字即可。

由于项目中没有针对性的进行数据库配置,所以timeout方法中会返回

(DriverManager.getLoginTimeout() * 1000);

这个就是关键了,这时去看下DriverManager.getLoginTimeout()的默认值,发现默认值是0.由于项目中,没有主动给这个赋值,也即使用的也是0

看了jdk的源代码,set方法中的注释有说明,为0时,表示无限制。也即不会超时,所以自己使用jdbc时,最好设置一个时间,否则万一出现一直等待

的情况就悲剧了。

/**
* Sets the maximum time in seconds that a driver will wait
* while attempting to connect to a database.
*
* @param seconds the login time limit in seconds; zero means there is no limit
* @see #getLoginTimeout
*/
public static void setLoginTimeout(int seconds) {
loginTimeout = seconds;
}

private static long timeout(Properties props)
{
String timeout = props.getProperty("loginTimeout");
if (timeout != null)
try {
return ()(Float.parseFloat(timeout) * 1000.0F);
}
catch (NumberFormatException e)
{
logger.debug("Couldn't parse loginTimeout value: " + timeout);
}

return (DriverManager.getLoginTimeout() * 1000); }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读