Zmq_client Listener Side code:
#Coding=utf8## client.pyImportZMQImportSYSImport TimeImportLoggingImportOshost='10.1.240.229'#The server is running a listening address that needs to match the listener address set in the server run script, if the same serverPORT ='4444'#the server is running a listening port that cannot be the same as the external business interfacelogging.basicconfig (filename='Subscriber.log', level=logging.info)classzclient (object):def __init__(Self, host=host, port=PORT):"""Initialize Worker"""Self.host=host Self.port=Port Self._context=ZMQ. Context () Self._subscriber=Self._context.socket (ZMQ. SUB)Print "Client initiated" defreceive_message (self):"""Start Receiving Messages"""Self._subscriber.connect ('tcp://{}:{}'. Format (Self.host, Self.port)) self._subscriber.setsockopt (ZMQ. SUBSCRIBE, b"") whileTrue:Print 'listening on tcp://{}:{}'. Format (self.host, self.port) message=self._subscriber.recv () time.sleep (1) Print "Sub", Message Time.sleep (100)#you can place tasks with very high latency Print "Sub", Message Logging.info ('{} - {}'. Format (message, Time.strftime ("%y-%m-%d%h:%m")))if __name__=='__main__': Zs=zclient () zs.receive_message ( )
Server-side code, where flask is used:
#Coding=utf8#server.pyImport TimeImportZMQImportJSONImportFlaskhost='10.1.240.229' #if written as 127.0.0.1, the default native IPPORT ='4444' #Listening Port_context=ZMQ. Context () _publisher=_context.socket (ZMQ. PUB) URL='tcp://{}:{}'. Format (HOST, PORT)defpublish_message (message):Try: _publisher.bind (URL) time.sleep (1) _publisher.send (message)exceptException as E:Print "Error {}". Format (e)finally: _publisher.unbind (URL) fromFlaskImportFlask fromFlaskImportRequest App= Flask (__name__) @app. Route ("/index/", methods=['POST']) deflowerstring (): Received_dict=json.loads (flask.request.data)#_strn = request.args.get (' param ') #response = ' lower case of {} is {} '. Format (_STRN, _strn.lower ()) #将请求转换成小写 #Print Received_dictResponse=received_dict ret=json.dumps (response) publish_message (ret)returnretif __name__=='__main__': Host="10.1.240.202"#External Service AddressPort = 7001#External Service Portdebug =True App.run (host, port, Debug)
When the user accesses the server's external service port, the server processes it, and the message is sent to the listener that listens to it, and then a message result is given to the user without concern about how the listener will handle it. After receiving the message from the server, the listener is processed and then the corresponding operation is done.
One of the benefits of this framework is to greatly improve the efficiency of the server, do not have to wait for the full processing to return, there is also a benefit is that the server and the listener can be deployed on different machines, according to the business requirements of reasonable deployment of hardware resources
The research of asynchronous communication using ZMQ Pub/sub+flask