Skip to content

Commit c86a7cd

Browse files
committed
Cria arquivo producer e consumer para exibir a mensagem "Hello World"
1 parent 9f59d92 commit c86a7cd

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
"main": "send.js",
66
"scripts": {
77
"test": "echo \"Error: no test specified\" && exit 1",
8-
"start": "node send.js && receive.js"
8+
"producer": "node src/send.js",
9+
"consumer": "node src/receive.js"
910
},
1011
"keywords": [],
1112
"author": "",

src/receive.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const amqp = require('amqplib/callback_api')
2+
3+
amqp.connect('amqp://localhost', (err, conn) => { // A configuração é a mesma que o send.js
4+
if (err) throw err
5+
6+
conn.createChannel((err, channel) => {
7+
if (err) throw err
8+
9+
// Declarando a queue no consumer
10+
const queue = 'hello'
11+
12+
channel.assertQueue(queue, {
13+
durable: false
14+
})
15+
16+
console.log(` [*] Waiting for messages in ${queue}. To exit press CTRL+C`)
17+
18+
channel.consume(queue, (message) => { // Funciona de forma assíncrona, espera a mensage e só exibe assim que o RabbitMQ enviar para o consumer
19+
console.log(` [x] Received: ${message.content.toString()}`)
20+
}, {
21+
noAck: true
22+
})
23+
})
24+
})

src/send.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const amqp = require('amqplib/callback_api')
2+
3+
amqp.connect('amqp://localhost', (err, conn) => { // Criando conexão no servidor
4+
if (err) throw err
5+
6+
conn.createChannel((err, channel) => { // Cria canal para desenvolver a maior parte da API
7+
if (err) throw err
8+
9+
// Declarando queue/fila
10+
const queue = 'hello'
11+
const message = 'Hello World!'
12+
13+
channel.assertQueue(queue, {
14+
durable: false
15+
})
16+
17+
channel.sendToQueue(queue, Buffer.from(message)) // O conteúdo é um array de bytes
18+
console.log(` [x] Sent: ${message}`)
19+
})
20+
21+
setTimeout(() => {
22+
conn.close()
23+
process.exit(0)
24+
}, 500) // Fecha conexão
25+
})

0 commit comments

Comments
 (0)