Python+zmq实现负载均衡

# encoding: utf-8

import zmq
import time
import random
from threading import Thread
from vbsl.config import *
from vbsl.get_logs import *
from vbsl.parse_logs import *

NBR_WORKERS = 30


def worker_thread(context=None):
    context = context or zmq.Context.instance()
    worker = context.socket(zmq.REQ)
    worker.connect("tcp://localhost:5671")

    total = 0
    while True:
        # Tell the router we're ready for work
        worker.send(b"ready")

        # Get workload from router, until finished
        workload = worker.recv_string()
        finished = workload == "END"
        if finished:
            print("Processed: %d tasks" % total)
            break
        total += 1

        # Do the work
        station = workload
        ip = get_ip(station)
        if ip is None:
            continue
        print(station, ip)
        file_name = f"/tmp/{station}-{get_date()}.log"
        if os.path.isfile(file_name):
            print(f"{file_name} exist.")
        else:
            print("start script")
            os.system(F"ssh jumper \"/home/bsp/IP/get_logs.sh {ip} {station} {get_date()}\"")


def main():
    context = zmq.Context.instance()
    client = context.socket(zmq.ROUTER)
    client.bind("tcp://*:5671")

    for _ in range(NBR_WORKERS):
        Thread(target=worker_thread).start()

    random.shuffle(STATIONS)
    print(len(STATIONS))
    print(STATIONS)

    for station in STATIONS:
        # LRU worker is next waiting in the queue
        address, empty, ready = client.recv_multipart()
        client.send_multipart([
            address,
            b'',
            bytes(station, encoding="utf-8"),
        ])
        time.sleep(1)

    # Now ask mama to shut down and report their results
    for _ in range(NBR_WORKERS):
        address, empty, ready = client.recv_multipart()
        client.send_multipart([
            address,
            b'',
            b'END',
        ])


if __name__ == "__main__":
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值