当业务量激增时,增减服务器是很频繁的事,每次手动修改配置文件的 upstream
并不是让人满意的做法,每次增加了服务器 nginx 可以自动刷新就好了,这时候需要使用到 upsync 模块。
安装模块
openresty 版本为 1.11.2.2,通过动态加载的方式导入。
下载并解压模块
1 | $ wget https://github.com/weibocom/nginx-upsync-module/archive/v2.0.0.tar.gz |
下载 openresty
1 | $ wget https://openresty.org/download/openresty-1.11.2.2.tar.gz |
编译安装
1 | $ ./configure --prefix=/usr/local/openresty --add-dynamic-module=../nginx-upsync-module-2.0.0 |
然后在 /usr/local/openresty/nginx/modules
目录下会出现 ngx_http_upsync_module.so
模块文件,然后在 nginx.conf 中导入
1 | load_module modules/ngx_http_upsync_module.so; |
etcd
upsync 模块支持 consul 和 etcd 两种服务发现服务,在这里我们使用 etcd,如果你不了解 etcd,请看这里
我们添加两个服务到 k/v
储存中
1 | $ etcdctl set upstreams/127.0.0.1:8001 '{"server": "127.0.0.1:8001"}' |
查看文件夹 upstreams/
1 | $ curl http://127.0.0.1:2379/v2/keys/upstreams/ |
upstream 配置
upstream 配置如下:
1 | upstream test { |
参数 upsync_dump_path
的作用在于将 upstreams/
的内容备份到本地,并作为 upstream
列表使用,servers_test.conf
内容如下
1 | server 127.0.0.1:8001 weight=1 max_fails=2 fail_timeout=10s; |
当 servers_test.conf
成功下载后,配置 server localhost:8003;
将不再生效,它仅仅是为了不让 nginx 报错而存在的。
upstream_show
的作用是返回当前服务列表
1 | $ curl localhost/upstream_list |
