首先聲明,這麼幹純粹是為了好玩。
通常我們用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()