|
1 | 1 | #!/usr/bin/env node
|
2 | 2 |
|
3 |
| -// Example of using a headers exchange |
4 |
| - |
5 |
| -var amqp = require('../') |
6 |
| - |
7 |
| -amqp.connect().then(function(conn) { |
8 |
| - return conn.createChannel().then(withChannel); |
9 |
| -}, console.error); |
10 |
| - |
11 |
| -function withChannel(ch) { |
12 |
| - // NB the type of the exchange is 'headers' |
13 |
| - ch.assertExchange('matching exchange', 'headers').then(function(ex) { |
14 |
| - ch.assertQueue().then(function(q) { |
15 |
| - bindAndConsume(ch, ex, q).then(function() { |
16 |
| - send(ch, ex); |
17 |
| - }); |
18 |
| - }); |
| 3 | +const amqp = require('../'); |
| 4 | + |
| 5 | +(async () => { |
| 6 | + |
| 7 | + const connection = await amqp.connect(); |
| 8 | + const channel = await connection.createChannel(); |
| 9 | + |
| 10 | + process.once('SIGINT', async () => { |
| 11 | + await channel.close(); |
| 12 | + await connection.close(); |
19 | 13 | });
|
20 |
| -} |
21 | 14 |
|
22 |
| -function bindAndConsume(ch, ex, q) { |
| 15 | + const { exchange } = await channel.assertExchange('matching exchange', 'headers'); |
| 16 | + const { queue } = await channel.assertQueue(); |
| 17 | + |
23 | 18 | // When using a headers exchange, the headers to be matched go in
|
24 | 19 | // the binding arguments. The routing key is ignore, so best left
|
25 | 20 | // empty.
|
26 | 21 |
|
27 | 22 | // 'x-match' is 'all' or 'any', meaning "all fields must match" or
|
28 | 23 | // "at least one field must match", respectively. The values to be
|
29 | 24 | // matched go in subsequent fields.
|
30 |
| - ch.bindQueue(q.queue, ex.exchange, '', {'x-match': 'any', |
31 |
| - 'foo': 'bar', |
32 |
| - 'baz': 'boo'}); |
33 |
| - return ch.consume(q.queue, function(msg) { |
34 |
| - console.log(msg.content.toString()); |
35 |
| - }, {noAck: true}); |
36 |
| -} |
37 |
| - |
38 |
| -function send(ch, ex) { |
39 |
| - // The headers for a message are given as an option to `publish`: |
40 |
| - ch.publish(ex.exchange, '', Buffer.from('hello'), {headers: {baz: 'boo'}}); |
41 |
| - ch.publish(ex.exchange, '', Buffer.from('world'), {headers: {foo: 'bar'}}); |
42 |
| -} |
| 25 | + await channel.bindQueue(queue, exchange, '', { |
| 26 | + 'x-match': 'any', |
| 27 | + 'foo': 'bar', |
| 28 | + 'baz': 'boo' |
| 29 | + }); |
| 30 | + |
| 31 | + await channel.consume(queue, (message) => { |
| 32 | + console.log(message.content.toString()); |
| 33 | + }, { noAck: true }); |
| 34 | + |
| 35 | + channel.publish(exchange, '', Buffer.from('hello'), { headers: { baz: 'boo' }}); |
| 36 | + channel.publish(exchange, '', Buffer.from('hello'), { headers: { foo: 'bar' }}); |
| 37 | + channel.publish(exchange, '', Buffer.from('lost'), { headers: { meh: 'nah' }}); |
| 38 | + |
| 39 | + console.log(' [x] To exit press CTRL+C.'); |
| 40 | +})(); |
0 commit comments