本項(xiàng)目中對(duì)于網(wǎng)關(guān)的要求:
1.流量控制
2.灰度發(fā)布
3.負(fù)載均衡
4.服務(wù)上線、下線不停服務(wù),不影響正常業(yè)務(wù)的運(yùn)行
網(wǎng)關(guān)架構(gòu)圖如下:

采用nginx+nginx-upsync-module+consul實(shí)現(xiàn)
nginx版本:1.9.2
consul版本:1.2.0
1.安裝consul
將下載的consul_1.2.0_linux_amd64.zip解壓后放到/usr/local/consul/目錄下
2.啟動(dòng)consul:
./consul agent -server -bootstrap-expect=1 -data-dir=/data/consul_data -node=192.168.10.112 -bind=192.168.10.112 -config-dir=/etc/consul.d -client 0.0.0.0 -ui
agent:運(yùn)行一個(gè)consul代理。
-server :切換代理到服務(wù)器模式。
-bootstrap :將服務(wù)器設(shè)置為引導(dǎo)模式。
-ui:啟用內(nèi)置的靜態(tài)web UI服務(wù)器。
-data-dir:路徑到數(shù)據(jù)目錄存儲(chǔ)代理狀態(tài)。
-bind:設(shè)置集群通信的綁定地址。
-client:設(shè)置用于綁定客戶(hù)端訪問(wèn)的地址。這包括RPC、DNS、HTTP和HTTPS(如果配置)。
-node:此節(jié)點(diǎn)的名稱(chēng)。 在集群中必須是唯一的,如果你運(yùn)行第2臺(tái)consul,可以寫(xiě)trade_server02、trade_server03等。
3.訪問(wèn)consul:
http://192.168.10.112:8500/ui

4.配置服務(wù):
key/Value中增加兩個(gè)服務(wù)列表,路徑upstreams/itms/


6.nginx安裝
nginx安裝需要編譯nginx-upsync-module:服務(wù)發(fā)現(xiàn)模塊
7.nginx&upstream配置
?nginx從consul的數(shù)據(jù)中心抓取。新的upstream配置如下:
upstream itms {
? # fake server otherwise ngx_http_upstream will report error when startup
? # 后端使用consul存儲(chǔ)
? upsync 192.168.10.112:8500/v1/kv/upstreams/itms upsync_timeout=6m upsync_interval=500ms upsync_type=consul strong_dependency=off;
? upsync_dump_path /usr/local/nginx/conf/servers/servers_test.conf;
? include /usr/local/nginx/conf/servers/servers_test.conf;
}
服務(wù)轉(zhuǎn)發(fā):
location /trade {
? ? proxy_pass http://itms;
}
查詢(xún)服務(wù)列表:
location = /upstream_show {
? ? upstream_show;
? }

8.測(cè)試
配置consul服務(wù)下的值測(cè)試
{"weight":12,"max_fails":2,"fail_timeout":10,"down":0}
1.down為?1表示單前的server暫時(shí)不參與負(fù)載,0表示參與
2.weight 默認(rèn)為1.weight越大,負(fù)載的權(quán)重就越大。
3.max_fails :允許請(qǐng)求失敗的次數(shù)默認(rèn)為1.當(dāng)超過(guò)最大次數(shù)時(shí),返回proxy_next_upstream 模塊定義的錯(cuò)誤
4.fail_timeout:max_fails次失敗后,暫停的時(shí)間。