This repository has been archived by the owner on Jul 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamqp.js
179 lines (158 loc) · 4.8 KB
/
amqp.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
const debug = require('debug')('dev:libs:amqp');
const amqp = require('amqplib');
const uuid = require('node-uuid');
const _ = require('lodash');
const Promise = require('bluebird');
debug( 'load');
class RPC {
constructor ( settings) {
if( _.isString( settings))
this.config = settings;
else {
if( !_.get( settings, 'user') || !_.get( settings, 'password'))
throw 'config_error';
this.config = `amqp://${settings.user}:${settings.password}@${_.get( settings, 'host', 'localhost')}:${_.get( settings, 'port', 5672)}${_.get( settings, 'vhost', '')}`;
}
this.connection = false;
}
async init() {
try {
debug( 'connect to mq');
this.connection = await amqp.connect( this.config);
this.closeTag = false;
this.onRPCList = [];
debug( 'connection build');
this.connection.on('close', () => {
this.connection = false;
debug( 'connection close!');
if( this.closeTag)
return;
setTimeout( async () => {
this.connection = await amqp.connect( this.config);
debug( 'connection reconnect!');
Promise.each( this.onRPCList, item => {
this.onRPC( item.qName, item.callback);
});
}, 1000 * 5);
});
this.connection.on('error', async err => {
console.log( err);
await this.connection.close();
});
this.ch = await this.connection.createChannel();
this.ch.on( 'error', e => {
debug( e);
});
} catch ( e) {
throw `connection error: ${e}`;
}
}
async close() {
try {
this.closeTag = true;
await this.connection.close();
} catch ( e) {
throw `connection error: ${e}`;
}
}
async callRPC ( qName, data, timeout = 30) {
let ch;
try {
if( !this.connection)
throw 'connection_not_init';
ch = await this.connection.createChannel();
// 這邊如果沒有把 channel prototype 的 exception 接起來,會造成再上一個層級的 connection exception
// 以致於 下面的 catch 就會失效
ch.on( 'error', e => {
debug( e);
});
debug( qName);
await ch.checkQueue( qName).catch(()=> {
throw 'un_exists_queue';
});
const qok = await ch.assertQueue( '', { exclusive: true, autoDelete: true });
return new Promise( async ( resolve, reject) => {
await ch.consume( qok.queue, msg => {
if( !msg)
return reject( 'amqp_got_null_return');
if( ch)
ch.close();
resolve( JSON.parse( msg.content.toString()));
}, { noAck: true });
ch.sendToQueue( qName, Buffer.from( _.isString( data) ? data : JSON.stringify( data)), { correlationId: uuid(), replyTo: qok.queue });
})
.timeout( 1000 * timeout, `Queue: ${qName} timeout`)
.catch( Promise.TimeoutError, e => {
ch.close();
throw e;
});
} catch( e) {
throw `callRPC error: ${e}`;
}
}
async callPublish ( exName, qName, data) {
try {
if( !this.connection)
throw 'connection_not_init';
if( !this.ch) {
this.ch = await this.connection.createChannel();
// 這邊如果沒有把 channel prototype 的 exception 接起來,會造成再上一個層級的 connection exception
// 以致於 下面的 catch 就會失效
this.ch.on( 'error', e => {
debug( e);
});
}
this.ch.publish( exName, qName, Buffer.from( _.isString( data) ? data: JSON.stringify( data)));
} catch ( e) {
throw `callPublish error: ${e}`;
}
}
async onRPC ( qName, callback) {
this.onRPCList.push( { qName, callback });
onRPC( this.connection, qName, callback);
}
static async quickStart( settings) {
const conn = new RPC( settings);
await conn.init();
return conn;
}
}
module.exports = RPC;
async function onRPC ( connection, qName, callback) {
let ch;
try {
if( !connection)
throw 'connection_not_init';
ch = await connection.createChannel();
await ch.assertQueue( qName, {
durable: false,
auto_delete:true
});
ch.prefetch( 10);
debug( `onRPC ${qName}`);
ch.consume( qName, msg => {
const data = JSON.parse( msg.content.toString());
return callback(
data,
out => {
let obj;
try {
obj = JSON.stringify( out);
} catch( e) {
obj = {
code: 500,
msg: 'error_occur_when_data_stringify'
};
}
ch.sendToQueue( msg.properties.replyTo,
Buffer.from( obj),
{ correlationId: msg.properties.correlationId });
ch.ack( msg);
}
);
});
} catch ( e) {
debug( `AMQP.onRPC error ${e}`);
debug( e.stack);
}
}