mysql - 如何显式修改数据库连接超时时间

 cz小屁孩865 发布于 2022-11-02 02:14

spring + mybatis

redis.incr(key); //redis计数加一

try{
    dbOPerHere(); //数据库操作
}catch (Exception e){
    //若数据库操作失败 减一
    redis.decr(key); 
}

想模拟网路异常 数据库连接超时异常 通过如下方式模拟数据库连接异常

sudo iptables -A INPUT -p tcp --dport 3306 -j DROP

但发现要等差不多三分钟 才会有超时异常
另外一个奇怪现象 同样的数据源配置 若换成测试服务器 超时时间为6分钟 不知何故

Caused by: java.net.ConnectException: Connection timed out

如何显式设置数据库连接超时时间(如超时时间5秒), 不管是配置数据源 还是 修改mysql服务器的变量?
使用的数据源如下

或修改mysql服务器变量

>show variables like '%timeout%';
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 10       |
| delayed_insert_timeout      | 300      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| rpl_stop_slave_timeout      | 31536000 |
| slave_net_timeout           | 3600     |
| wait_timeout                | 28800    |
+-----------------------------+----------+
1 个回答
  •  /**
         * <strong>BasicDataSource does NOT support this method. </strong>
         *
         * <p>Set the login timeout (in seconds) for connecting to the
         * database.</p>
         * <p>
         * Calls {@link #createDataSource()}, so has the side effect
         * of initializing the connection pool.</p>
         *
         * @param loginTimeout The new login timeout, or zero for no timeout
         * @throws UnsupportedOperationException If the DataSource implementation
         *   does not support the login timeout feature.
         * @throws SQLException if a database access error occurs
         */
        public void setLoginTimeout(int loginTimeout) throws SQLException {
            // This method isn't supported by the PoolingDataSource returned by
            // the createDataSource
            throw new UnsupportedOperationException("Not supported by BasicDataSource");
            //createDataSource().setLoginTimeout(loginTimeout);
        }
    
    * <strong>BasicDataSource does NOT support this method. </strong>  *

    以上是dbcp连接池的源代码,不知道这个LoginTimeout()具体是做什么的,仅供参考,并期待问题后续。

    2022-11-03 14:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有