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()
相关推荐
Stara05111 小时前
Linux系统常用操作与命令指南
linux·vim
white.tie1 小时前
linux配置nginx
linux·运维·nginx
Komorebi.py2 小时前
【Linux】-学习笔记03
linux·笔记·学习
dessler2 小时前
云计算&虚拟化-kvm创建网桥(bridge)
linux·运维·云计算
YRr YRr2 小时前
Ubuntu20.04 解决一段时间后键盘卡死的问题 ubuntu
linux·数据库·ubuntu
何曾参静谧2 小时前
「Py」模块篇 之 PyAutoGUI库自动化图形用户界面库
运维·python·自动化
一只哒布刘3 小时前
RHCE-DNS域名解析服务器
运维·服务器
醇氧4 小时前
ab (Apache Bench)的使用
linux·学习·centos·apache
sss-web12264 小时前
4.远程访问及控制
运维·服务器
moneyxjj4 小时前
Linux各种解压命令汇总
linux·运维·服务器