1. 程式人生 > >【Nginx】如何使用Nginx實現MySQL資料庫的負載均衡?看完我懂了!!

【Nginx】如何使用Nginx實現MySQL資料庫的負載均衡?看完我懂了!!

## 寫在前面 > Nginx能夠實現HTTP、HTTPS協議的負載均衡,也能夠實現TCP協議的負載均衡。那麼,問題來了,可不可以通過Nginx實現MySQL資料庫的負載均衡呢?答案是:可以。接下來,就讓我們一起探討下如何使用Nginx實現MySQL的負載均衡。 ## 前提條件 **注意:使用Nginx實現MySQL資料庫的負載均衡,前提是要搭建MySQL的主主複製環境,關於MySQL主主複製環境的搭建,後續會在MySQL專題為大家詳細闡述。這裡,我們假設已經搭建好MySQL的主主複製環境,MySQL伺服器的IP和埠分別如下所示。** * 192.168.1.101 3306 * 192.168.1.102 3306 通過Nginx訪問MySQL的IP和埠如下所示。 * 192.168.1.100 3306 ## Nginx實現MySQL負載均衡 nginx在版本1.9.0以後支援tcp的負載均衡,具體可以參照官網關於模組[ngx_stream_core_module](http://nginx.org/en/docs/stream/ngx_stream_core_module.html#tcp_nodelay)的敘述,連結地址為:http://nginx.org/en/docs/stream/ngx_stream_core_module.html#tcp_nodelay。 nginx從1.9.0後引入模組ngx_stream_core_module,模組是沒有編譯的,需要用到編譯,編譯時需新增--with-stream配置引數,stream負載均衡官方配置樣例如下所示。 ```bash worker_processes auto; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } stream { upstream backend { hash $remote_addr consistent; server backend1.example.com:12345 weight=5; server 127.0.0.1:12345 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; } upstream dns { server 192.168.0.1:53535; server dns.example.com:53; } server { listen 12345; proxy_connect_timeout 1s; proxy_timeout 3s; proxy_pass backend; } server { listen 127.0.0.1:53 udp; proxy_responses 1; proxy_timeout 20s; proxy_pass dns; } server { listen [::1]:12345; proxy_pass unix:/tmp/stream.socket; } } ``` 說到這裡,使用Nginx實現MySQL的負載均衡就比較簡單了。我們可以參照上面官方的配置示例來配置MySQL的負載均衡。這裡,我們可以將Nginx配置成如下所示。 ```bash user nginx; #user root; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } stream{ upstream mysql{ server 192.168.1.101:3306 weight=1; server 192.168.1.102:3306 weight=1; } server{ listen 3306; server_name 192.168.1.100; proxy_pass mysql; } } ``` 配置完成後,我們就可以通過如下方式來訪問MySQL資料庫。 ```bash jdbc:mysql://192.168.1.100:3306/資料庫名稱 ``` 此時,Nginx會將訪問MySQL的請求路由到IP地址為192.168.1.101和192.168.1.102的MySQL上。 **好了,今天就聊到這兒吧!別忘了點個贊,給個在看和轉發,讓更多的人看到,一起學習,一起進步!!** ## 寫在最後 > 如果你覺得冰河寫的還不錯,請微信搜尋並關注「 **冰河技術** 」微信公眾號,跟冰河學習高併發、分散式、微服務、大資料、網際網路和雲原生技術,「 **冰河技術** 」微信公眾號更新了大量技術專題,每一篇技術文章乾貨滿滿!不少讀者已經通過閱讀「 **冰河技術** 」微信公眾號文章,吊打面試官,成功跳槽到大廠;也有不少讀者實現了技術上的飛躍,成為公司的技術骨幹!如果你也想像他們一樣提升自己的能力,實現技術能力的飛躍,進大廠,升職加薪,那就關注「 **冰河技術** 」微信公眾號吧,每天更新超硬核技術乾貨,讓你對如何提升技術能力不再迷茫! ![](https://img-blog.csdnimg.cn/202007162204436