一、Consul
Consul是一款開源的分佈式服務註冊與發現系統,通過HTTP API可以使得服務註冊、發現實現起來非常簡單。
1.1 環境搭建
下載:wget https://releases.hashicorp.com/consul/0.7.1/consul_0.7.1_linux_amd64.zip
解壓:unzip consul_0.7.1_linux_amd64.zip
出現以上內容就表示安裝成功了!
啓動:./consul agent -dev -ui -node=consul-dev -client=192.168.179.129
注意關閉防火牆,瀏覽器訪問端口 8500 出現管理界面(管理負載均衡配置存放信息)搭建完成.
1.2註冊Http服務
使用Postman訪問,添加信息,存放負載均衡配置
Datacenter指定數據中心,Address指定服務IP,Service.Id指定服務唯一標識,Service.Service指定服務分組,Service.tags指定服務標籤(如測試環境、預發環境等),Service.Port指定服務端口。
可以看到這邊已經添加上了
再次添加一個8081端口的服務
二、nginx-upsync-module
Upsync是新浪微博開源的基於Nginx實現動態配置的三方模塊。Nginx-Upsync-Module的功能是拉取Consul的後端server的列表,並動態更新Nginx的路由信息。此模塊不依賴於任何第三方模塊。Consul作爲Nginx的DB,利用Consul的KV服務,每個Nginx Work進程獨立的去拉取各個upstream的配置,並更新各自的路由。
1.1安裝使用
安裝nginx:wget http://nginx.org/download/nginx-1.9.10.tar.gz
解壓:tar -zxvf nginx-1.9.10.tar.gz
配置:
groupadd nginx useradd -g nginx -s /sbin/nologin nginx mkdir -p /var/tmp/nginx/client/ mkdir -p /usr/local/nginx |
進入目錄 :
cd nginx-1.9.10
編譯Nginx (如報錯缺少openssl 執行 yum -y install openssl openssl-devel):
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy/ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre --add-module=../nginx-upsync-module-master
make && make install
安裝nginx-upsync-module:wget https://github.com/weibocom/nginx-upsync-module/archive/master.zip 解壓
1.2Upstream 動態配置:
首先先創建upsync_dump_path:
mkdir /usr/local/nginx/conf/servers/
upsync_dump_path指定從consul拉取的上游服務器後持久化到的位置,這樣即使consul服務器出問題了,本地還有一個備份。
upsync指令指定從consul哪個路徑拉取上游服務器配置;upsync_timeout配置從consul拉取上游服務器配置的超時時間;upsync_interval配置從consul拉取上游服務器配置的間隔時間;upsync_type指定使用consul配置服務器;strong_dependency配置nginx在啓動時是否強制依賴配置服務器,如果配置爲on,則拉取配置失敗時nginx啓動同樣失敗。upsync_dump_path指定從consul拉取的上游服務器後持久化到的位置,這樣即使consul服務器出問題了,本地還有一個備份。
##動態去consul 獲取註冊的真實反向代理地址
upstream test{
server 127.0.0.1:11111;
upsync 192.168.179.129:8500/v1/kv/upstreams/test upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;
upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://test;
index index.html index.htm;
}
}
啓動nginx
最後再啓動consul:
./consul agent -dev -ui -node=consul-dev -client=192.168.179.129
使用postman發送put請求來配置負責均衡:
可以看到,添加了8081和8082端口
好了 配置到這裏就結束了,訪問nginx發現負載均衡配置完成,現可以很方便的動態配置nginx。