最近同事遇到一个问题,使用python开发的工具在执行的时候无法和MySQL建立连接,其最直接的现象就是满篇的TIME_WAIT,最后通过调整tcp_timestamps参数问题得以解决,再次记录一下这次解决的经验总结。
ps:不过先汗颜一个,对基础的tcp知识太不敏感了,需要回炉重新学习啊。
一、看下TIME_WAIT产生的原因
大家都知道建立连接是著名的三次握手机制。
那么如何关闭连接呢? 其实也是著名的四次握手机制。
TIME_WAIT就产生在四次握手的的主动关闭方,而server端会进入close状态。
那么TIME_WAIT什么时候会消失呢?LINUX会在2MSL时间内消失。(MSL是最大分段生存期,默认为2分钟)
二、无法建立连接的原因
由于同事的脚本的用途是进行采集数据后的写入操作,为了加快速度故使用python的map功能并发写入数据库,当在脚本执行的服务器上报错后,发现满篇都是TIME_WAIT的现象。
经过我们内部讨论,初步认为是由于TIME_WAT没有快速回收导致Linux的可用端口被沾满导致无发建立连接,和MySQL的设置没有关系。
查看目前Linux可用端口范围:
[me]sysctl -a|grep ip_local_port_range net.ipv4.ip_local_port_range = 3276861000
查看当前占用的端口直接用netstat就可以了:
netstat -nat|grep -i time_wait|wc -l
三、如何解决?
对于TCP链接的优化大家都知道的三个参数:tcp_tw_reuse、tcp_tw_recycle、tcp_timestamp
1、我们先看看这3个参数的定义和作用。
tcp_tw_reuse:用来使用time-wait状态的sockets重用
Allow to reuse TIME-WAIT sockets for new connections when it is<br>safe from protocol viewpoint. Default value is 0.It should not be changed without advice/request of technical experts.
tcp_tw_recycle:用来加速对time-wait
Enable fast recycling TIME-WAIT sockets. Default value is 0.It should not be changed without advice/request of technical experts.
tcp_timestamp:在TCP的包头添加时间戳
Enable timestamps as defined in RFC1323
2、调整记录
我们先查看服务器的状态,发现reuse和recycle的参数都是1,但是time_wait并没有被很快的回收,也没有被快速的重用。
[root ~]# cat /proc/sys/net/ipv4/tcp_tw_reuse 1[root ~]# cat /proc/sys/net/ipv4/tcp_tw_recycle 1
后来发现是由于tcp_timestamp这个参数设置为0的原因
[root ~] cat /proc/sys/net/ipv4/tcp_timestamps 0
将这个参数置为1之后,time_wati的状态立刻下降了很多,脚本也可以正常执行了。看来tcp_timestamp非常关键。
3、探寻原因
但是,究竟是tcp_tw_reuse起作用了? 还是tcp_tw_recycle起作用了?我们还是不知道,只能从现象得知问题解决了。
我们将tcp_tw_recycle的值设定为0之后,再次测试,再次出现了大量的time_wait现象。
为了证明tcp_tw_recycle真正起作用了,我们再次将tcp_tw_reuse参数设置为1,这时候也再次出现了大量的time_wait的现象。
看来,最终我们的结论是同时开启tcp_tw_recycle,tcp_tw_reuse和tcp_timestamp才能真正做到快速回收和服用time-wait状态的socket。
从stackoverflow上看到的一个答案比较靠谱。点这里
但是同时也发现,网上有很多信息显示,如果同时开启tcp_tw_recycle和tcp_timestamp会出现问题。主要是由于TCP的一种行为
<strong>RFC 1323 TCP Extensions for High Performance Jacobson, Braden, & Borman</strong>
An additional mechanism could be added to the TCP, a per-hostcache of the last timestamp received from any connection.This value could then be used in the PAWS mechanism to rejectold duplicate segments from earlier incarnations of theconnection, if the timestamp clock can be guaranteed to haveticked at least once since the old connection was open.Thiswould require that the TIME-WAIT delay plus the RTT togethermust be at least one tick of the sender's timestamp clock.Such an extension is not part of the proposal of this RFC.
三、结论
1、开启tcp_timestamp是开启tcp_tw_recycle,tcp_tw_reuse和tcp_timestamp的前提条件。
2、但是在nat模式下,不用将tcp_tw_recycle和tcp_timestamp同时开启,这会造成tcp超时引发故障。
附录:
https://www.kernel.org/doc/Documentation/networking/ip-sysctl.txt
http://lxr.free-electrons.com/source/net/ipv4/tcp_minisocks.c#L92
http://www.ietf.org/rfc/rfc1323.txt

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use