Created
April 1, 2024 20:32
-
-
Save gmsotavio/ffd39c1ddbe72208e45bd68bc0926cbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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