欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

MySQL查询超时的设置方法

程序员文章站 2022-04-25 17:49:30
...

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 这里顺带解释一下什么是non-interactive connection Non-Interactive Commands Just do a quick look up on a table without logging into the client, running the query then logging back out aga

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

  这里顺带解释一下什么是non-interactive connection

  > Non-Interactive Commands

  Just do a quick look up on a table without logging into the client, running the query then logging back out again.

  You can instead just type one line using the ' -e ' flag.

  [sql]

  c:\mysql\bin\mysql -u admin -p myDatabase -e 'SELECT * FROM employee'

  net_read_timeout / net_write_timeout

  The number of seconds to wait for more data from a connection before aborting the read. Before MySQL 5.1.41, this timeout applies only to TCP/IP connections, not to connections made through Unix socket files, named pipes, or shared memory. When the server is reading from the client, net_read_timeout is the timeout value controlling when to abort. When the server is writing to the client, net_write_timeout is the timeout value controlling when to abort. See also slave_net_timeout.

  On Linux, the NO_ALarm build flag affects timeout behavior as indicated in the description of the net_retry_count system variable.

  解释:这个参数只对TCP/IP链接有效,分别是数据库等待接收客户端发送网络包和发送网络包给客户端的超时时间,这是在Activity状态下的线程才有效的参数

  JDBC setQueryTimeout函数:

  为了避免查询出现死循环,或时间过长等现象,而导致线程阻塞,在获得Statement的实例后,stmt.setQueryTimeout(10); 避免因为查询导致程序出现线程阻塞。

  但昨天发现程序出现了,“ORA-01013: 用户请求取消当前的操作”的异常。手工执行出错SQL语句发现,这个语句耗时20多秒。因为setQueryTimeout(10),所以还没有执行完查询语句就抛出异常了。使用setQueryTimeout(10)时一定要把时间设置的长一些,如60秒以上。只要不导致线程长期阻塞,就可以。太短了容易抛出,“ORA-01013: 用户请求取消当前的操作”的异常

  JDBC实现setQueryTimeout的原理:

  [java]

  class IfxCancelQueryImpl extends TimerTask

  implements IfmxCancelQuery

  {

  IfxStatement stmt;

  Timer t = null;

  public void startCancel(IfxStatement paramIfxStatement, int paramInt)

  throws Exception

  {

  this.stmt = paramIfxStatement;

  this.t = new Timer(true);

  this.t.schedule(this, paramInt * 1000);

  }

  public void run()

  {

  try

  {

  this.stmt.cancel();

  this.t.cancel();

  }

  catch (SQLException localSQLException)

  {

  this.t.cancel();

  throw new Error(localSQLException.getErrorCode() + ":" + localSQLException.getMessage());

  }

  }

  }

  可见,query timeout是通过客户端解决方案来做的,服务器端无需知晓。通过一个timer线程来监控执行时间,如果执行时间超时,则会schedule run()函数。

[1] [2]

MySQL查询超时的设置方法