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

超时时间问题

这个现场环境遇到过,程序一直处于等待状态,大致是因为没有设置超时时间,默认是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);
  }

 

 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值