After one, this is done purely for fun.
The example in the previous blog can only handle a server to a client situation, today modified a version that can support a server to multiple client. The implementation is that the server throws a single action into a thread, the client is similar to each received a data, a thread to do their own logic. This looks a bit like a socket into a.
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 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 h
Andle (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 (ke Y, 5) Server = Server () Server.start () client = client () Client.start ()