pubsub.py 640 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
22
23
import os, time, random, 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")

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

i = 1
while True:
    msg = f"Message { i }"
    i = i + 1 
    n = random.randint(1, 3)
    time.sleep(n)
    print(f"Publishing message '{ msg }' to channel '{ channel }'")
    try:
        stream.publish(channel, json.dumps({
            "timestamp": time.time_ns(),
            "message": msg
        }))
    except Exception as ex:
        print(f"Could not publish message '{msg}' caused by {ex}")