First of all, this is done purely for fun.
Usually we use Redis mainly to store some data, because the data is in memory, so the query updates quickly. We can also use the PUB/SUB function to implement message publishing/subscription. But today we are going to talk about how to implement server-client synchronous communication through the Redis list. specific needs
The client side runs the request that is distributed on the server side, then performs some action and returns the result to the server side. implementation idea using Redis's list data structure, using blocking POPs to implement client-side waiting to distribute commands and Server-side wait return results. First the server side generates a globally unique key, and the key and data are pushed together into one of our designated queues, this is "myqueue". After Lpush, the server side uses Brpop to wait for the result to be returned from the "key" queue and set the timeout time to 2 seconds. Client-side startup, using Brpop from the specified queue to obtain the distribution of commands, once received server-side data, the client will get key and data, and then do some of their own processing, processing completed, the "key" queue Lpush execution results. Finally, the server end uses Brpop to obtain execution results from the "key" queue. Implementation Code
Import Redis Import time import JSON import threading host = ' localhost ' port = 6322 queue = ' Myqueue ' class Server (THR Eading. 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 ' Ser
Ver: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 ()