Redis實作類別似同步方法調用的功能(二)

來源:互聯網
上載者:User

接上一篇,這麼幹純粹是為了好玩。

上一篇的部落格中的例子只能處理一個Server對一個Client的情況,今天修改了一版,可以支援一個Server對多個Client。實現方式就是Server每派發一個動作就扔到一個線程裡去,Client也類似每收到一個資料,就起一個線程去做自己的邏輯。這樣看起來就有點像socket變成了。

import redisimport timeimport jsonimport threadinghost = 'localhost'port = 6322queue = '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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.