Messaging between PythonGo and external apps

PythonGo has packaged lots of functions within the software itself. It is hard to directly code and debug the application, but it does offer the access to Python, so that you can code anything from collecting tick data to complex strategies. This entry tries to show how technically we can publish and subscribe messages via python, which is helpful for us to enable PythonGo for such messaging later on.

Listener class

class MessageListener:
    def __init__(self,name,channel):
        self.name=name
        self.channel=channel
    def listen(self,r):
        if r:
            listener = r.pubsub()
            listener.subscribe(self.channel)
            for message in listener.listen():
                print(f"{self.name} has message: {message}")
        else:
            print('please create redis connection.')
    #build a function to unsubscribe as well to terminate threads.

Listener Thread

import threading
import redis
r=redis.Redis(host='localhost', port=6379, db=0)
listener1=MessageListener('l1','channel1')
listener2=MessageListener('l2','channel1')
t1=threading.Thread(target=listener1.listen,args=(r,))
t2=threading.Thread(target=listener2.listen,args=(r,))
t1.start()
t2.start()

Publisher

import redis
r=redis.Redis(host='localhost', port=6379, db=0)
r.publish('channel1',"hello from publisher")

Reference: