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()
相关推荐
ghostwritten1 分钟前
k8s黑科技:Linux+Vagrant+VirtualBox开启Kubernetes奇幻之旅
linux·科技·kubernetes
the_nov22 分钟前
14.网络套接字TCP
linux·c++·网络协议
电星托马斯28 分钟前
C++中顺序容器vector、list和deque的使用方法
linux·c语言·c++·windows·笔记·学习·程序人生
LCY1331 小时前
spring 中的DAO是什么
运维·git·jenkins
爱写代码的小朋友1 小时前
华三交换机配置常用命令
运维·服务器·网络
愿你天黑有灯下雨有伞1 小时前
Docker 安装 Elasticsearch 教程
运维·elasticsearch·docker
遇见火星1 小时前
自动化发布工具CI/CD实践Jenkins常用工具和插件的使用
运维·ci/cd·自动化·jenkins·自动化发布
愚润求学2 小时前
【Linux】Linux权限
linux·服务器·语法
低头不见2 小时前
一个服务器算分布式吗,分布式需要几个服务器
运维·服务器·分布式
麻芝汤圆2 小时前
使用 MapReduce 进行高效数据清洗:从理论到实践
大数据·linux·服务器·网络·数据库·windows·mapreduce