pubsub-producer.py 708 Bytes
Newer Older
1
import os, time, random, json, socket
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
2
3
4
5
import redis

host = os.environ.get("REDIS_SVC", "redis-svc")
port = int(os.environ.get("REDIS_PORT", "6379"))
Nane Kratzke's avatar
Nane Kratzke committed
6
channel = os.environ.get("CHANNEL", "xpubsub")
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
7
8
9

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

10
me = socket.gethostname()
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
11
12
i = 1
while True:
Nane Kratzke's avatar
Nane Kratzke committed
13
    msg = f"Hi, this is message #{ i } from { me }."
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
14
    i = i + 1 
Nane Kratzke's avatar
Nane Kratzke committed
15
16
    n = random.randint(1, 5)
    time.sleep(n / 10)
Nane Kratzke's avatar
pubsub  
Nane Kratzke committed
17
18
19
20
21
22
23
24
    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}")