suchen
HeimDatenbankMySQL-Tutorialmysql连接超时的参数设置_MySQL

最近系统因为数据库连接超时的问题,出现了几次故障。排查了下my.cnf的配置问题,最后是代码设计有问题。正好就把所有的timeout参数都理一遍,首先数据库里查一下看有哪些超时:

 

mysql> show global variables like "%timeout%";

+-----------------------------+----------+

| Variable_name               | Value    |

+-----------------------------+----------+

| connect_timeout             | 10       |

| delayed_insert_timeout      | 300      |

| innodb_flush_log_at_timeout | 1        |

| innodb_lock_wait_timeout    | 120      |

| 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    |

+-----------------------------+----------+

12 rows in set (0.00 sec)

 

我们来分析下各个参数的意义:

connect_timeout

 

手册描述:

The number of seconds that the mysqld server waits for a connect packet before responding with Bad handshake. The default value is 10 seconds as of MySQL 5.1.23 and 5 seconds before that.

Increasing the connect_timeout value might help if clients frequently encounter errors of the form Lost connection to MySQL server at ‘XXX’, system error: errno.

 

解释:在获取链接时,等待握手的超时时间,只在登录时有效,登录成功这个参数就不管事了。主要是为了防止网络不佳时应用重连导致连接数涨太快,一般默认即可。

 

delayed_insert_timeout

 

手册描述:

How many seconds an INSERT DELAYED handler thread should wait for INSERT statements before terminating.

解释:这是为MyISAM INSERT DELAY设计的超时参数,在INSERT DELAY中止前等待INSERT语句的时间。

 

innodb_lock_wait_timeout

 

手册描述:

The timeout in seconds an InnoDB transaction may wait for a row lock before giving up. The default value is 50 seconds. A transaction that tries to access a row that is locked by another InnoDB transaction will hang for at most this many seconds before issuing the following error:

 

1

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

When a lock wait timeout occurs, the current statement is not executed. The current transaction is not rolled back. (To have the entire transaction roll back, start the server with the –innodb_rollback_on_timeout option, available as of MySQL 5.1.15. See also Section 13.6.12, “InnoDB Error Handling”.)

innodb_lock_wait_timeout applies to InnoDB row locks only. A MySQL table lock does not happen inside InnoDB and this timeout does not apply to waits for table locks.

InnoDB does detect transaction deadlocks in its own lock table immediately and rolls back one transaction. The lock wait timeout value does not apply to such a wait.

For the built-in InnoDB, this variable can be set only at server startup. For InnoDB Plugin, it can be set at startup or changed at runtime, and has both global and session values.

 

解释:描述很长,简而言之,就是事务遇到锁等待时的Query超时时间。跟死锁不一样,InnoDB一旦检测到死锁立刻就会回滚代价小的那个事务,锁等待是没有死锁的情况下一个事务持有另一个事务需要的锁资源,被回滚的肯定是请求锁的那个Query。

innodb_rollback_on_timeout

 

手册描述:

In MySQL 5.1, InnoDB rolls back only the last statement on a transaction timeout by default. If –innodb_rollback_on_timeout is specified, a transaction timeout causes InnoDB to abort and roll back the entire transaction (the same behavior as in MySQL 4.1). This variable was added in MySQL 5.1.15.

 

解释:这个参数关闭或不存在的话遇到超时只回滚事务最后一个Query,打开的话事务遇到超时就回滚整个事务。

 

interactive_timeout/wait_timeout

手册描述:

The number of seconds the server waits for activity on an interactive connection before closing it. An interactive client is defined as a client that uses the CLIENT_INTERACTIVE option to mysql_real_connect(). See also

解释:一个持续SLEEP状态的线程多久被关闭。线程每次被使用都会被唤醒为acrivity状态,执行完Query后成为interactive状态,重新开始计时。wait_timeout不同在于只作用于TCP/IP和Socket链接的线程,意义是一样的。一般设置是8小时,一般网站白天都有人访问,从夜里到早上一般都会超过8小时,所以再来访问就会这个问题。

 

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状态下的线程才有效的参数

 

slave_net_timeout

手册描述:

The number of seconds to wait for more data from the master before the slave considers the connection broken, aborts the read, and tries to reconnect. The first retry occurs immediately after the timeout. The interval between retries is controlled by the MASTER_CONNECT_RETRY option for the CHANGE MASTER TO statement or –master-connect-retry option, and the number of reconnection attempts is limited by the –master-retry-count option. The default is 3600 seconds (one hour).

解释:这是Slave判断主机是否挂掉的超时设置,在设定时间内依然没有获取到Master的回应就人为Master挂掉了

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Das Beherrschen der Methode zum Hinzufügen von MySQL -Benutzern ist für Datenbankadministratoren und -entwickler von entscheidender Bedeutung, da sie die Sicherheits- und Zugriffskontrolle der Datenbank gewährleistet. 1) Erstellen Sie einen neuen Benutzer, der den Befehl createUser verwendet, 2) Berechtigungen über den Zuschussbefehl zuweisen, 3) Verwenden Sie FlushPrivileges, um sicherzustellen, dass die Berechtigungen wirksam werden.

Beherrschen MySQL -Zeichenfolge Datentypen: VARCHAR v.Stext vs. charBeherrschen MySQL -Zeichenfolge Datentypen: VARCHAR v.Stext vs. charMay 12, 2025 am 12:12 AM

ChooSeCharforfixed-LengthData, varcharforvariable-LengthData, undTextForLargetEXTFields.1) Charisefficiefforconsistent-LengthDatalikeCodes.2) varcharSefficienpyficyFoximent-Länge-Länge.3) VarcharSuitsVariable-Lengthdatalikenamen, BalancingFlexibilityPerance.3) textissideale

MySQL: String -Datentypen und Indizierung: Best PracticesMySQL: String -Datentypen und Indizierung: Best PracticesMay 12, 2025 am 12:11 AM

Best Practices für die Handhabung von String -Datentypen und -indizes in MySQL gehören: 1) Auswählen des entsprechenden Zeichenfolge -Typs, z. B. Zeichen für feste Länge, Varchar für variable Länge und Text für großen Text; 2) bei der Indexierung vorsichtig sein, über die Indexierung vermeiden und Indizes für gemeinsame Abfragen erstellen; 3) Verwenden Sie Präfixindizes und Volltextindizes, um lange String-Suchvorgänge zu optimieren. 4) Überwachen und optimieren Sie die Indizes regelmäßig, um die Indizes gering und effizient zu halten. Mit diesen Methoden können wir Lese- und Schreibleistung in Einklang bringen und die Datenbankeffizienz verbessern.

MySQL: So fügen Sie einen Benutzer aus der Ferne hinzuMySQL: So fügen Sie einen Benutzer aus der Ferne hinzuMay 12, 2025 am 12:10 AM

Toaddauerremotelytomysql, folge thesesteps: 1) connectTomysqlasroot, 2) CreateeNewuserWithremoteAccess, 3) Grant -nöterPrivilegeges und 4) flushprivileges.BecauTiousousousousous-

Die ultimative Anleitung zu MySQL -String -Datentypen: Effiziente DatenspeicherungDie ultimative Anleitung zu MySQL -String -Datentypen: Effiziente DatenspeicherungMay 12, 2025 am 12:05 AM

TostorestringseffictionlyInmysql, ChoosetherightDatatypeDonyourneeds: 1) UsecharforFixed-LengthSlikeCountrycodes.2) UseVarcharforVariable-LengthStringSlikenMamen.3) useTextforlong-formtextContent.-We useblob formainbherinaryImimages

MySQL Blob vs. Text: Auswählen des richtigen Datentyps für große ObjekteMySQL Blob vs. Text: Auswählen des richtigen Datentyps für große ObjekteMay 11, 2025 am 12:13 AM

Bei der Auswahl der Blob- und Textdatentypen von MySQL eignet sich Blob für die Speicherung von Binärdaten und der Text ist zum Speichern von Textdaten geeignet. 1) Der Blob eignet sich für binäre Daten wie Bilder und Audio, 2) Text ist für Textdaten wie Artikel und Kommentare geeignet. Bei der Auswahl müssen Dateneigenschaften und Leistungsoptimierung berücksichtigt werden.

MySQL: Soll ich Root -Benutzer für mein Produkt verwenden?MySQL: Soll ich Root -Benutzer für mein Produkt verwenden?May 11, 2025 am 12:11 AM

Nein, YouShouldnotusetheroTusserinMysqlForyourProduct.instead, Createspecificusers withlimitedPrivileGeenhiteSecurity und 1) CreateOnewuserWithaStrongPassword, 2) Grantonlyn -DegetaryPothisuser, 3) regelmäßigem LyRegPassUtupdatusuSerpermings

MySQL -String -Datentypen erläutert: Wählen Sie den richtigen Typ für Ihre Daten ausMySQL -String -Datentypen erläutert: Wählen Sie den richtigen Typ für Ihre Daten ausMay 11, 2025 am 12:10 AM

MysqlstringDatatypessHouldbechosenbasedonDatacharacteristics undsecases: 1) UseCharforfixed-LengthStringslikecountrycodes.2) UseVarcharforvariable-Länge-Längestringslikenames.3) VerwendungBinaryorvarbinaryChryCryEcryEcryCryPlyptography.4) gebrauch

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

Nordhold: Fusionssystem, erklärt
3 Wochen vorBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Flüstern des Hexenbaum
3 Wochen vorBy尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

SublimeText3 Linux neue Version

SublimeText3 Linux neue Version

SublimeText3 Linux neueste Version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Leistungsstarke integrierte PHP-Entwicklungsumgebung

SecLists

SecLists

SecLists ist der ultimative Begleiter für Sicherheitstester. Dabei handelt es sich um eine Sammlung verschiedener Arten von Listen, die häufig bei Sicherheitsbewertungen verwendet werden, an einem Ort. SecLists trägt dazu bei, Sicherheitstests effizienter und produktiver zu gestalten, indem es bequem alle Listen bereitstellt, die ein Sicherheitstester benötigen könnte. Zu den Listentypen gehören Benutzernamen, Passwörter, URLs, Fuzzing-Payloads, Muster für vertrauliche Daten, Web-Shells und mehr. Der Tester kann dieses Repository einfach auf einen neuen Testcomputer übertragen und hat dann Zugriff auf alle Arten von Listen, die er benötigt.

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools

PHPStorm Mac-Version

PHPStorm Mac-Version

Das neueste (2018.2.1) professionelle, integrierte PHP-Entwicklungstool