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

來源:互聯網
上載者:User

首先聲明,這麼幹純粹是為了好玩。

通常我們用Redis主要是為了儲存一些資料,由於資料在記憶體裡,所以查詢更新很快。同時我們也可以利用 Pub/Sub 功能來實現訊息發布/訂閱。但是今天我們來說說怎麼通過Redis的list來實現 Server - Client 的同步通訊。 具體需求

Client 端運行後監聽 Server 端派發的請求,然後執行一些操作,並將結果返回給 Server 端。 實現想法 利用 Redis 的 list 資料結構,使用阻塞 pop 的方式實現 Client 端等待派發命令和 Server 端等待返回結果。 首先Server端產生一個全域唯一的key,並將key和data一起push到我們指定的一個隊列裡,這裡是“myqueue”。lpush之後,Server端就使用brpop等待從“key”隊列返回結果,並設定逾時時間為2秒。 Client端啟動後,使用brpop從指定的隊列裡擷取派發的命令,一旦收到Server端派發的資料,Client就會擷取key和data,然後做自己的一些處理,處理完成後,就往“key”隊列裡lpush執行結果。 最後,Server端會從“key”隊列裡使用brpop擷取執行結果。 實現代碼

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            request = {'id': key, 'data': data}            print 'Server: Send request: %s' % request            conn.lpush(queue, json.dumps(request))            response = conn.brpop(key, 2)            if response:                print 'Server: Receive response: %s' % response[1]            else:                print "Server: Timeout!!!"            time.sleep(1)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]            print 'Client: Receive request: %s' % msg            time.sleep(0.1)            d = json.loads(msg)            key = d.get('id')            d['data'] = "response_" + key            print 'Client: Send response: %s' % d            conn.lpush(key, json.dumps(d))            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.