1.安装环境
sudo apt update
sudo apt install python3 python3-pip nginx
2.python代码
1)服务代码
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f"Served by backend server on port {self.server.server_port}".encode())
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8001):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on port {port}")
httpd.serve_forever()
if __name__ == '__main__':
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8001
run(port=port)
python3 backend.py 8001 &
python3 backend.py 8002 &
python3 backend.py 8003 &
2)编写负载均衡器
from http.server import HTTPServer, BaseHTTPRequestHandler
import random
import http.client
# 后端服务器列表
backend_servers = [
('localhost', 8001),
('localhost', 8002),
('localhost', 8003)
]
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 随机选择一个后端服务器
backend_server = random.choice(backend_servers)
self.proxy_to(backend_server)
def proxy_to(self, backend_server):
conn = http.client.HTTPConnection(*backend_server)
conn.request('GET', self.path)
response = conn.getresponse()
self.send_response(response.status)
for header, value in response.getheaders():
self.send_header(header, value)
self.end_headers()
self.wfile.write(response.read())
conn.close()
def run(server_class=HTTPServer, handler_class=RequestHandler, addr="0.0.0.0", port=8000):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
run()
python3 load_balancer.py &
3.nginx配置
编辑Nginx配置文件 /etc/nginx/sites-available/default
(或创建一个新的配置文件):
server {
listen 80;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
sudo systemctl restart nginx
4.访问你的ip就可以看到效果了
5.增加权重
修改load_balancer.py文件的代码
from http.server import HTTPServer, BaseHTTPRequestHandler
import random
import http.client
# 后端服务器列表,包含权重
backend_servers = [
('localhost', 8001, 3), # 权重为3
('localhost', 8002, 1), # 权重为1
('localhost', 8003, 1) # 权重为1
]
# 扩展服务器列表,根据权重增加出现次数
weighted_servers = []
for server, port, weight in backend_servers:
weighted_servers.extend([(server, port)] * weight)
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 随机选择一个后端服务器
backend_server = random.choice(weighted_servers)
self.proxy_to(backend_server)
def proxy_to(self, backend_server):
conn = http.client.HTTPConnection(*backend_server)
conn.request('GET', self.path)
response = conn.getresponse()
self.send_response(response.status)
for header, value in response.getheaders():
self.send_header(header, value)
self.end_headers()
self.wfile.write(response.read())
conn.close()
def run(server_class=HTTPServer, handler_class=RequestHandler, addr="0.0.0.0", port=8000):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
run()