ubuntu实现负载均衡

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()
相关推荐
热爱编程的小白白6 小时前
【Playwright自动化】录制生成脚本
运维·自动化
java_logo6 小时前
MySQL Server Docker 容器化部署指南
linux·运维·数据库·docker·容器
I***t7167 小时前
自己编译RustDesk,并将自建ID服务器和key信息写入客户端
运维·服务器
誰能久伴不乏7 小时前
Linux文件套接字AF_UNIX
linux·服务器·c语言·c++·unix
BJ_Bonree7 小时前
数智先锋 | 核心应用响应时常<1s、多终端崩溃率低至 0.1%!Bonree ONE 赋能蓝月亮应用性能与终端体验双重升级!
运维
张鱼小丸子7 小时前
电脑刷机教程:轻松重装系统指南
运维
a41324477 小时前
如何解决centos上oracle连接问题
linux·oracle·centos
h***34637 小时前
在linux(Centos)中Mysql的端口修改保姆级教程
linux·mysql·centos
星释7 小时前
Rust 练习册 97:Run-Length Encoding 压缩算法
java·linux·rust