Skip to content

Instantly share code, notes, and snippets.

@gmsotavio
Created April 1, 2024 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmsotavio/ffd39c1ddbe72208e45bd68bc0926cbe to your computer and use it in GitHub Desktop.
Save gmsotavio/ffd39c1ddbe72208e45bd68bc0926cbe to your computer and use it in GitHub Desktop.
import redis
import time
import threading
# Conectando ao servidor Redis
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
# Função para publicar números sequenciais a cada 100ms
def publish_numbers():
count = 0
while count < 10:
count += 1
redis_client.publish('sequence_channel', str(count))
time.sleep(0.01)
print("Publisher finished")
# Função para subscrever e imprimir os valores
def subscribe_and_print():
pubsub = redis_client.pubsub()
pubsub.subscribe('sequence_channel')
while True:
message = pubsub.get_message()
if message and message['type'] == 'message':
print("Received:", message['data'].decode('utf-8'))
# Aguarda um curto período para evitar uso excessivo da CPU
time.sleep(1)
# Iniciando as threads para publicar e subscrever
publish_thread = threading.Thread(target=publish_numbers)
subscribe_thread = threading.Thread(target=subscribe_and_print)
publish_thread.start()
subscribe_thread.start()
while True:
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment