Redis实现类似同步方法调用的功能(二)

接上一篇,这么干纯粹是为了好玩。

上一篇的博客中的例子只能处理一个Server对一个Client的情况,今天修改了一版,可以支持一个Server对多个Client。实现方式就是Server每派发一个动作就扔到一个线程里去,Client也类似每收到一个数据,就起一个线程去做自己的逻辑。这样看起来就有点像socket变成了。

import redis
import time
import json
import threading

host = 'localhost'
port = 6322
queue = 'myqueue'


class Server(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
        conn = redis.Redis(connection_pool=pool)
        idx = 0

        while True:
            idx = idx + 1

            key = str(idx)
            data = "request_" + key

            threading.Thread(target=ServerHandler(conn, key, data).handle).start()

            time.sleep(1)


class ServerHandler(object):

    def __init__(self, conn, key, data):
        self.conn = conn
        self.key = key
        self.data = data

    def handle(self):
        request = {'id': self.key, 'data': self.data}
        print 'Server: Send request: %s' % request
        self.conn.lpush(queue, json.dumps(request))

        response = self.conn.brpop(self.key, 2)
        if response:
            print 'Server: Receive response: %s' % response[1]
        else:
            print "Server: Timeout!!!"


class Client(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        pool = redis.BlockingConnectionPool(host=host, port=port, db='0')
        conn = redis.Redis(connection_pool=pool)

        while True:
            msg = conn.brpop(queue)[1]
            threading.Thread(target=ClientHandler(conn, msg).handle).start()


class ClientHandler(object):

    def __init__(self, conn, msg):
        self.conn = conn
        self.msg = msg

    def handle(self):
        print 'Client: Receive request: %s' % self.msg

        time.sleep(0.1)

        d = json.loads(self.msg)
        key = d.get('id')
        d['data'] = "response_" + key
        print 'Client: Send response: %s' % d
        self.conn.lpush(key, json.dumps(d))
        self.conn.expire(key, 5)


server = Server()
server.start()

client = Client()
client.start()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 网络编程 一.楔子 你现在已经学会了写python代码,假如你写了两个python文件a.py和b.py,分别去运...
    go以恒阅读 6,430评论 0 6
  • 首先声明,这么干纯粹是为了好玩。 通常我们用Redis主要是为了存储一些数据,由于数据在内存里,所以查询更新很快。...
    kongxx阅读 4,394评论 0 0
  • 最近在学习Python看了一篇文章写得不错,是在脚本之家里的,原文如下,很有帮助: 一、网络知识的一些介绍 soc...
    qtruip阅读 7,694评论 0 6
  • 本文出自 Eddy Wiki ,转载请注明出处:http://eddy.wiki/interview-java.h...
    eddy_wiki阅读 6,632评论 0 14
  • 我童年的最好的小伙伴小霞要回来了。 我在老家住了一个月有余了,大雪封路的情况得到了一些缓解,人们出门也基本上恢复了...
    过客匆匆W阅读 994评论 0 2