-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketamqp.js
93 lines (76 loc) · 2.42 KB
/
socketamqp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const WebSocket = require("ws");
const Connection = require("rabbitmq-client").Connection;
const {Kafka} = require("kafkajs");
// Initialize:
const rabbit = new Connection('amqp://guest:guest@localhost:5672')
rabbit.on('error', (err) => {
console.log('RabbitMQ connection error', err)
})
rabbit.on('connection', () => {
console.log('Connection successfully (re)established')
})
const PORT = 3000;
const DEFAULT_INTERVAL = 10000;
// Create a WebSocket server
const wss = new WebSocket.Server({ port: PORT });
let webs = null;
wss.on("connection", (ws) => {
console.log("Client connected");
webs = ws;
//Send random numbers at the specified interval
// const generateRandomNumbers = () => {
// if (ws.readyState === WebSocket.OPEN) {
// console.log(messages.length);
// ws.send(1, (err) => {
// console.log(err);
// });
// }
// };
// // Default interval is 1 second
//let timer = setInterval(generateRandomNumbers, DEFAULT_INTERVAL);
ws.on("message", async (message) => {
try {
const kafka = new Kafka({
"clientId": "1001",
"brokers": ["localhost:9092"]
});
const producer = kafka.producer();
await producer.connect();
console.log('connected');
console.log(message.toString());
const partition = 0;
const result = await producer.send({
"topic": "msganalysistopic",
"messages": [{"value": message, "partition": partition}]
})
console.log(`Sent Successfully - ${JSON.stringify(result)}`);
await producer.disconnect();
} catch (ex) {
console.error(ex);
}
});
ws.on("close", () => {
console.log("Client disconnected");
// clearInterval(timer);
});
});
console.log(`WebSocket server listening on port ${PORT}`);
const sub = rabbit.createConsumer({
queue: 'msg-analysis-receiver-queue',
queueOptions: {durable: false},
// handle 2 messages at a time
qos: {prefetchCount: 1}
}, (msg) => {
const result = {
...msg.body,
receiverId: msg.consumerTag,
receiverQueue: msg.routingKey,
receiverTime: new Date().toDateString()
};
console.log(result);
if (webs.readyState === WebSocket.OPEN) {
webs.send(JSON.stringify(result));
}
});
// Consume messages from a queue:
// See API docs for all options