$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.00s Running `target/debug/proxy_pass` server0 Running on on 127.0.0.1:3000 server1 Running on on 127.0.0.1:3001 server3 Running on on 127.0.0.1:3003 server2 Running on on 127.0.0.1:3002
#!/bin/sh # test.sh declare -A servers servers=( ["Response from server0"]=0 ["Response from server1"]=0 ["Response from server2"]=0 ["Response from server3"]=0 )
TOTAL=20
for ((i=0; i<$TOTAL; i++)) { resp=$(curl --silent localhost:80) echo$resp let servers["$resp"]++ } echo"Server 0:"${servers["Response from server0"]} echo"Server 1:"${servers["Response from server1"]} echo"Server 2:"${servers["Response from server2"]} echo"Server 3:"${servers["Response from server3"]}
这个脚本使用curl向nginx代理服务器发送请求
然后使用echo回显请求内容,并时相应计数器加一
最后echo打印各个服务器的响应情况
运行测试可以看到如下内容,
1 2 3 4 5 6 7 8 9 10 11 12 13 14
$ ./test.sh Response from server0 Response from server1 Response from server2 Response from server3 ... Response from server0 Response from server1 Response from server2 Response from server3 Server 0: 5 Server 1: 5 Server 2: 5 Server 3: 5
可以看到,响应的会依次来自服务器0、1、2、3,然后再次循环。这就是轮询的含义
固定权值方式
更改配置文件如下
1 2 3 4 5 6 7 8
http { upstream myserver { server 127.0.0.1:3000 weight=1; server 127.0.0.1:3001 weight=3; server 127.0.0.1:3002 weight=2; server 127.0.0.1:3003 weight=4; } }
$ ./test.sh Response from server3 Response from server2 Response from server1 Response from server3 Response from server3 Response from server1 ... Response from server0 Response from server1 Response from server3 Response from server2 Response from server1 Response from server3 Server 0: 2 Server 1: 6 Server 2: 4 Server 3: 8