DAS_2023_1/sergeev_evgenii_lab_4/publisher.py

32 lines
1.0 KiB
Python
Raw Normal View History

2024-01-22 00:58:41 +04:00
import pika
import time
import json
import random
class LecturePublisher:
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
self.channel = self.connection.channel()
self.channel.exchange_declare(exchange='lecture_exchange', exchange_type='fanout')
def publish_lecture_event(self):
lecture_event = {
'event_type': 'new_lecture',
'lecture_id': random.randint(1, 100),
'topic': f'Lecture on Topic {random.randint(1, 10)}',
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
self.channel.basic_publish(exchange='lecture_exchange', routing_key='', body=json.dumps(lecture_event))
print(f" [x] Sent lecture event: {lecture_event}")
if __name__ == '__main__':
lecture_publisher = LecturePublisher()
try:
while True:
lecture_publisher.publish_lecture_event()
time.sleep(1)
except KeyboardInterrupt:
lecture_publisher.connection.close()