配置加权轮询的负载均衡,nginx.conf如下:
#user nobody;
worker_processes 4;
error_log logs/debug.log debug;
events {
worker_connections 1024;
}
http {
#include mime.types;
#default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
upstream myserver
{
server 127.0.0.1:6666 weight=2; # 配置权重
server 127.0.0.1:7777 weight=1;
}
server {
client_max_body_size 4G;
listen 80;
root /data;
location ~*.mp4$ {
proxy_pass http://myserver; # 代理到myserver
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
}
}
server {
client_max_body_size 4G;
listen 127.0.0.1:6666;
root /data;
location ~*.mp4$ {
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
add_header host "127.0.0.1:6666"; # 设置响应中的host
}
}
server {
client_max_body_size 4G;
listen 127.0.0.1:7777;
root /data;
location ~*.mp4$ {
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
add_header host "127.0.0.1:7777";
}
}
}
首先还是使用了反向代理proxy_pass的功能
proxy_pass http://myserver; # 代理到myserver
myserver配置如下:
upstream myserver
{
server 127.0.0.1:6666 weight=2; # 配置权重
server 127.0.0.1:7777 weight=1;
}
本地6666端口占2/3的权重,7777端口占1/3的权重。
编写测试脚本
#!/bin/bash
for ((i=0;i<3;i++));do
curl -L -v http://192.168.116.130:80/a.mp4 -o 1.mp4
done
执行输入如下:
# bash test.sh 2>1.txt && cat 1.txt | egrep host:
< host: 127.0.0.1:6666
< host: 127.0.0.1:7777
< host: 127.0.0.1:6666
可以看到访问6666和7777的比例是2:1,符合配置的权重。