Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const amqp = require('amqplib');
- // RabbitMQ connection parameters
- const rabbitmqHost = 'amqp://TMDG2022:TMDG2022@rmq2.pptik.id:5672/';
- const rabbitmqQueue = 'numbers_queue';
- async function connect() {
- try {
- // Connect to RabbitMQ
- const connection = await amqp.connect(rabbitmqHost);
- const channel = await connection.createChannel();
- // Declare the queue
- await channel.assertQueue(rabbitmqQueue, {
- durable: true
- });
- // Callback function for receiving messages
- const receiveMessageCallback = async (msg) => {
- const message = msg.content.toString();
- const seconds = parseInt(message);
- // Countdown from the received number of seconds
- countdown(seconds);
- console.log(`Received number: ${seconds}`);
- channel.ack(msg);
- };
- // Start consuming messages from the queue
- channel.consume(rabbitmqQueue, receiveMessageCallback, { noAck: false });
- console.log('Waiting for messages...');
- } catch (error) {
- console.error('Error:', error);
- }
- }
- function countdown(seconds) {
- for (let i = seconds; i > 0; i--) {
- console.log(`Countdown: ${i} seconds`);
- sleepSync(1000);
- }
- }
- function sleepSync(ms) {
- const startTime = new Date().getTime();
- while (new Date().getTime() - startTime < ms) {}
- }
- // Start the script
- connect();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement