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()
相关推荐
dntktop25 分钟前
解锁自动化新高度,zTasker v2.0全方位提升效率
运维·windows
花姐夫Jun1 小时前
在 CentOS 8 系统上安装 Jenkins 的全过程
linux·centos·jenkins
运维&陈同学1 小时前
【Beats01】企业级日志分析系统ELK之Metricbeat与Heartbeat 监控
运维·elk·elasticsearch·云原生·kibana·heartbeat·metricbeat
地球资源数据云1 小时前
全国30米分辨率逐年植被覆盖度(FVC)数据集
大数据·运维·服务器·数据库·均值算法
是店小二呀1 小时前
【Linux】Linux开发利器:make与Makefile自动化构建详解
linux·运维·自动化
baihb10242 小时前
Jenkins 构建流水线
运维·jenkins
BUG 4042 小时前
LINUX--shell
linux·运维·服务器
菜鸟小白:长岛icetea2 小时前
Linux零基础速成篇一(理论+实操)
linux·运维·服务器
深海的鲸同学 luvi2 小时前
【HarmonyOS NEXT】hdc环境变量配置
linux·windows·harmonyos
dowhileprogramming3 小时前
Python 中的迭代器
linux·数据库·python