Last active
May 23, 2024 04:38
-
-
Save andreconghau/b55250f76b0e3738d6ec08ddc1210d0f to your computer and use it in GitHub Desktop.
RabbitMQ Publish & Consume with Durable - Persistent message. It help rabbitMQ keep messages after reboot
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
version: "3.2" | |
services: | |
rabbitmq: | |
image: rabbitmq:3-management-alpine | |
container_name: "rabbitmq" | |
ports: | |
- 5672:5672 | |
- 15672:15672 | |
volumes: | |
- ./data/rabbitmq/data/:/var/lib/rabbitmq/ | |
- ./data/rabbitmq/log/:/var/log/rabbitmq | |
networks: | |
- my_net | |
networks: | |
my_net: | |
driver: bridge |
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
const amqp = require("amqplib/callback_api"); | |
function publishToQueue(queueName, message) { | |
amqp.connect("amqp://localhost", function (error0, connection) { | |
if (error0) { | |
throw error0; | |
} | |
connection.createChannel(function (error1, channel) { | |
if (error1) { | |
throw error1; | |
} | |
channel.assertQueue(queueName, { | |
durable: true, // Make queue durable | |
}); | |
channel.sendToQueue(queueName, Buffer.from(message), { | |
persistent: true, // Make messages persistent | |
}); | |
console.log(" [x] Sent %s", message); | |
// Close the connection after sending the message | |
channel.close(function (error) { | |
if (error) { | |
throw error; | |
} | |
connection.close(); | |
}); | |
}); | |
}); | |
} | |
function moveMessage(sourceQueue, targetQueue) { | |
amqp.connect("amqp://localhost", function (error0, connection) { | |
if (error0) { | |
throw error0; | |
} | |
connection.createChannel(function (error1, channel) { | |
if (error1) { | |
throw error1; | |
} | |
channel.assertQueue(sourceQueue, { | |
durable: true, | |
}); | |
channel.assertQueue(targetQueue, { | |
durable: true, | |
}); | |
channel.consume(sourceQueue, function (msg) { | |
const message = msg.content.toString(); | |
console.log(" Consume: ", message); | |
console.log(" [x] Received %s from %s", message, sourceQueue); | |
channel.sendToQueue(targetQueue, Buffer.from(message), { | |
persistent: true, | |
}); | |
console.log(" [x] Sent %s to %s", message, targetQueue); | |
channel.ack(msg); | |
}); | |
setTimeout(function () { | |
channel.close(); | |
connection.close(); | |
}, 500); | |
}); | |
}); | |
} | |
// TODO: Publish | |
publishToQueue("myQueue", "Hello, RabbitMQ!"); | |
// TODO: Consume | |
// moveMessage("myQueue", "myOtherQueue"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment