|
| 1 | +const q = 'tasks'; |
| 2 | + |
| 3 | +const { execSync } = require("child_process"); |
| 4 | +const amqplib = require("amqplib"); |
| 5 | + |
| 6 | +async function createConnection() { |
| 7 | + const id = Math.round(Math.random() * 1000); |
| 8 | + console.log(`* connect ${id}`); |
| 9 | + const pconn = amqplib.connect("amqp://root:[email protected]:5672/").then((conn) => { |
| 10 | + conn.on("close", (error) => { |
| 11 | + console.log(`* connection closed ${id}:`, error); |
| 12 | + }); |
| 13 | + conn.on("error", (error) => { |
| 14 | + console.log(`* connection error ${id}:`, error); |
| 15 | + }); |
| 16 | + return conn; |
| 17 | + }); |
| 18 | + console.log(`* connected ${id}`); |
| 19 | + return pconn; |
| 20 | +} |
| 21 | + |
| 22 | +async function createChannel(conn) { |
| 23 | + const id = Math.round(Math.random() * 1000); |
| 24 | + console.log(`* create channel ${id}`); |
| 25 | + const channel = conn.createChannel({durable: false}); |
| 26 | + console.log(`* channel created ${id}`); |
| 27 | + return channel; |
| 28 | +} |
| 29 | + |
| 30 | +async function createConnectionAndChannel() { |
| 31 | + const conn = await createConnection(); |
| 32 | + const channel = await createChannel(conn); |
| 33 | + return channel; |
| 34 | +} |
| 35 | + |
| 36 | +async function main(channels) { |
| 37 | + |
| 38 | + if (!channels) { |
| 39 | + channels = await Promise.all([createConnectionAndChannel(), createConnectionAndChannel()]); |
| 40 | + } |
| 41 | + const [publisherChannel, consumerChannel] = channels; |
| 42 | + |
| 43 | + // publisher |
| 44 | + console.log("publish"); |
| 45 | + await publisherChannel.assertQueue(q).then(function(ok) { |
| 46 | + console.log("published"); |
| 47 | + return publisherChannel.sendToQueue(q, Buffer.from("something to do")); |
| 48 | + }); |
| 49 | + |
| 50 | + // consumer |
| 51 | + console.log("consume"); |
| 52 | + await consumerChannel.assertQueue(q).then(function(ok) { |
| 53 | + console.log("consumed"); |
| 54 | + return consumerChannel.consume(q, function(msg) { |
| 55 | + if (msg !== null) { |
| 56 | + console.log(msg.content.toString()); |
| 57 | + consumerChannel.ack(msg); |
| 58 | + } |
| 59 | + }); |
| 60 | + }); |
| 61 | + |
| 62 | + await new Promise((resolve, reject) => { |
| 63 | + setTimeout(resolve, 1000); |
| 64 | + }); |
| 65 | + |
| 66 | + await main(channels); |
| 67 | +} |
| 68 | + |
| 69 | +main(); |
0 commit comments