Python与multiprocessing.Manager共享网络套接字

3 投票
3 回答
5386 浏览
提问于 2025-04-16 08:39

我现在正在写一个nginx代理服务器模块,在它前面加了一个请求队列,这样当后面的服务器处理不过来的请求时,就不会丢掉这些请求(nginx被设置成了负载均衡器)。

我使用的是

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

我的想法是先把请求放到一个队列里再处理。我知道multiprocessing.Queue只支持简单的对象,不能支持原始的套接字,所以我尝试使用multiprocess.Manager来创建一个共享字典。可是,Manager也使用套接字来连接,所以这个方法也失败了。有没有办法在不同的进程之间共享网络套接字呢?这里是代码中有问题的部分:

class ProxyServer(Threader, HTTPServer):

    def __init__(self, server_address, bind_and_activate=True):
        HTTPServer.__init__(self, server_address, ProxyHandler,
                bind_and_activate)

        self.manager = multiprocessing.Manager()

        self.conn_dict = self.manager.dict()
        self.ticket_queue = multiprocessing.Queue(maxsize= 10)
        self._processes = []
        self.add_worker(5)


    def process_request(self, request, client):
        stamp = time.time()
        print "We are processing"

        self.conn_dict[stamp] = (request, client) # the program crashes here


    #Exception happened during processing of request from ('172.28.192.34', 49294)
    #Traceback (most recent call last):
    #  File "/usr/lib64/python2.6/SocketServer.py", line 281, in _handle_request_noblock
    #    self.process_request(request, client_address)
    #  File "./nxproxy.py", line 157, in process_request
    #    self.conn_dict[stamp] = (request, client)
    #  File "<string>", line 2, in __setitem__
    #  File "/usr/lib64/python2.6/multiprocessing/managers.py", line 725, in _callmethod
    #    conn.send((self._id, methodname, args, kwds))
    #TypeError: expected string or Unicode object, NoneType found

        self.ticket_queue.put(stamp)


    def add_worker(self, number_of_workers):
        for worker in range(number_of_workers):
            print "Starting worker %d" % worker
            proc = multiprocessing.Process(target=self._worker, args = (self.conn_dict,))
            self._processes.append(proc)
            proc.start()

    def _worker(self, conn_dict):
        while 1:
            ticket = self.ticket_queue.get()

            print conn_dict
            a=0
            while a==0:
                try:
                    request, client = conn_dict[ticket]
                    a=1
                except Exception:
                    pass
            print "We are threading!"
            self.threader(request, client)

3 个回答

0

你可以看看这段代码 - https://gist.github.com/sunilmallya/4662837,这段代码是一个使用多进程的套接字服务器。它的工作原理是,父进程在接受连接后,把这些连接传递给客户端。

0

看起来你需要在进程之间传递文件描述符(这里假设你在用Unix系统,不太了解Windows)。我自己在Python中从来没有做过这个,不过这里有一个链接,指向一个叫做python-passfd的项目,你可以去看看。

7

你可以使用multiprocessing.reduction来在不同的进程之间传递连接和套接字对象。

示例代码

# Main process
from multiprocessing.reduction import reduce_handle
h = reduce_handle(client_socket.fileno())
pipe_to_worker.send(h)

# Worker process
from multiprocessing.reduction import rebuild_handle
h = pipe.recv()
fd = rebuild_handle(h)
client_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
client_socket.send("hello from the worker process\r\n") 

撰写回答