Using Nginx's stream module to implement MySQL reverse proxy and RabbitMQ load balancing
Why use the stream module?
- TCP level proxy: MySQL and RabbitMQ are both TCP-based protocols, not HTTP.
stream
Module allows Nginx to proxy at the TCP level, allowing it to handle non-HTTP traffic. - Protocol Transparency: Using
stream
modules, Nginx does not parse the MySQL or AMQP protocols, which means it can pass data seamlessly, maintaining protocol integrity. - Performance and High Availability: By distributing connections across multiple backend servers,
stream
the module enables load balancing, improving performance and high availability. - Flexibility: Using
stream
modules, you can proxy almost any TCP or UDP-based service, making Nginx a powerful network proxy tool.
How to introduce stream module in nginx?
Add the module during ./configure
--with-stream
./configure --prefix=/usr/local/nginx --with-stream
Implement MySQL reverse proxy in nginx configuration file
The following is the reverse proxy implementation, 3306 to 10002
stream {
server {
listen 10002;
proxy_connect_timeout 5s;
proxy_timeout 300s;
proxy_pass 127.0.0.1:3306;
}
}
http { # ...其他HTTP配置... }
Implementing RabbitMQ load balancing in nginx configuration file
stream {
upstream rabbitmq_nodes {
server 127.0.0.1:5672 max_fails=3 fail_timeout=30s; # 第一个节点
server 127.0.0.1:5673 max_fails=3 fail_timeout=30s; # 第二个节点
server 127.0.0.1:5674 max_fails=3 fail_timeout=30s; # 第三个节点
# 健康检查
}
server {
listen 5675;
proxy_pass rabbitmq_nodes;
}
}