pubsub.py 594 Bytes
Newer Older
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os, time, json
import redis

host = os.environ.get("REDIS_SVC", "redis-svc")
port = int(os.environ.get("REDIS_PORT", "6379"))
channel = os.environ.get("CHANNEL", "xfan")

r = redis.Redis(host=host, port=port, db=0)

ch = r.pubsub()
ch.subscribe(channel)

for msg in ch.listen():
    try:
        r = time.time_ns()
        data = json.loads(msg['data'].decode('utf8'))
        latency = (r - data['timestamp']) / 1000 / 1000
        print(f"{latency:.2f}ms | msg: { json.dumps(data) }")
    except Exception as ex:
        print(f"Could not process message '{ msg }' caused by { ex }")