-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathclient.js.html
1083 lines (966 loc) · 30.4 KB
/
client.js.html
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>MQ Nodejs HTTP SDK Documents Source: client.js</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cosmo.css">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MQ Nodejs HTTP SDK Documents</a>
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="topNavigation">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="MessageProperties.html">MessageProperties</a></li><li><a href="MQClient.html">MQClient</a></li><li><a href="MQConsumer.html">MQConsumer</a></li><li><a href="MQProducer.html">MQProducer</a></li><li><a href="MQTransProducer.html">MQTransProducer</a></li>
</ul>
</li>
</ul>
<div class="col-sm-3 col-md-3">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
<div class="input-group-btn">
<button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container" id="toc-content">
<div class="row">
<div class="col-md-12">
<div id="main">
<h1 class="page-title">Source: client.js</h1>
<section>
<article>
<pre
class="sunlight-highlight-javascript linenums">'use strict';
const assert = require('assert');
const debug = require('debug')('mq:client');
const httpx = require('httpx');
const kitx = require('kitx');
const {
toXMLBuffer,
parseXML,
extract,
getCanonicalizedMQHeaders,
processMsgProperties
} = require('./helper');
/**
* MQ的client,用于保存aliyun账号消息,以及发送http请求
*/
class MQClient {
/**
* MQClient构造函数
* @param {string} endpoint MQ的HTTP接入地址
* @param {string} accessKeyId 阿里云账号的AK
* @param {string} accessKeySecret 阿里云账号的SK
* @param {string} securityToken 阿里云RAM授权的STS TOKEN,可空
*
* @returns {MQClient}
*/
constructor(endpoint, accessKeyId, accessKeySecret, securityToken) {
assert(endpoint, '"endpoint" must be passed in');
this.endpoint = endpoint;
assert(accessKeyId, 'must pass in "accessKeyId"');
this.accessKeyId = accessKeyId;
assert(accessKeySecret, 'must pass in "accessKeySecret"');
this.accessKeySecret = accessKeySecret;
// security token
this.securityToken = securityToken;
}
/**
* 发送http请求
* @param {string} method HTTP的请求方法GET/PUT/POST/DELETE...
* @param {string} resource HTTP请求URL的path
* @param {string} type 解析XML响应内容的元素名字
* @param {string} requestBody 请求的body
* @param {object} opts 额外请求的参数
*
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "xxxxxxxxxxxxxx",
* body: {A:1,B:2,C:3}
* }
* ```json
*/
async request(method, resource, type, requestBody, opts = {}) {
const url = `${this.endpoint}${resource}`;
debug('url: %s', url);
debug('method: %s', method);
const headers = this.buildHeaders(method, requestBody, resource, opts.headers);
debug('request headers: %j', headers);
debug('request body: %s', requestBody.toString());
const response = await httpx.request(url, Object.assign(opts, {
method: method,
headers: headers,
data: requestBody
}));
debug('statusCode %s', response.statusCode);
debug('response headers: %j', response.headers);
const code = response.statusCode;
const contentType = response.headers['content-type'] || '';
const responseBody = await httpx.read(response, 'utf8');
debug('response body: %s', responseBody);
var body;
if (responseBody && (contentType.startsWith('text/xml') || contentType.startsWith('application/xml'))) {
const responseData = await parseXML(responseBody);
if (responseData.Error) {
const e = responseData.Error;
const message = extract(e.Message);
const requestid = extract(e.RequestId);
//const hostid = extract(e.HostId);
const errorcode = extract(e.Code);
const err = new Error(`${method} ${url} failed with ${code}. ` +
`RequestId: ${requestid}, ErrorCode: ${errorcode}, ErrorMsg: ${message}`);
err.Code = errorcode;
err.RequestId = requestid;
throw err;
}
body = {};
Object.keys(responseData[type]).forEach((key) => {
if (key !== '$') {
body[key] = extract(responseData[type][key]);
}
});
}
return {
code,
requestId: response.headers['x-mq-request-id'],
body: body
};
}
/**
* 发送HTTP GET请求
*
* @param {string} resource HTTP请求URL的path
* @param {string} type 解析XML响应内容的元素名字
* @param {object} opts 额外请求的参数
*
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "xxxxxxxxxxxxxx",
* body: {A:1,B:2,C:3}
* }
* ```
*/
get(resource, type, opts) {
return this.request('GET', resource, type, '', opts);
}
/**
* 发送HTTP POST请求
*
* @param {string} resource HTTP请求URL的path
* @param {string} type 解析XML响应内容的元素名字
* @param {string} requestBody 请求的body
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "xxxxxxxxxxxxxx",
* body: {A:1,B:2,C:3}
* }
* ```
*/
post(resource, type, body) {
return this.request('POST', resource, type, body);
}
/**
* 发送HTTP DELETE请求
*
* @param {string} resource HTTP请求URL的path
* @param {string} type 解析XML响应内容的元素名字
* @param {string} requestBody 请求的body
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "xxxxxxxxxxxxxx",
* body: {A:1,B:2,C:3}
* }
* ```
*/
delete(resource, type, body) {
return this.request('DELETE', resource, type, body);
}
/**
* 对请求的内容按照MQ的HTTP协议签名,sha1+base64
* @param {string} method 请求方法
* @param {object} headers 请求头
* @param {string} resource HTTP请求URL的path
*
* @returns {string} 签名
*/
sign(method, headers, resource) {
const canonicalizedMQHeaders = getCanonicalizedMQHeaders(headers);
const md5 = headers['content-md5'] || '';
const date = headers['date'];
const type = headers['content-type'] || '';
var toSignString = `${method}\n${md5}\n${type}\n${date}\n${canonicalizedMQHeaders}${resource}`;
var buff = Buffer.from(toSignString, 'utf8');
const degist = kitx.sha1(buff, this.accessKeySecret, 'binary');
return Buffer.from(degist, 'binary').toString('base64');
}
/**
* 组装请求MQ需要的请求头
* @param {string} method 请求方法
* @param {string} body 请求内容
* @param {string} resource HTTP请求URL的path
*
* @returns {object} headers
*/
buildHeaders(method, body, resource) {
const date = new Date().toGMTString();
const headers = {
'date': date,
'x-mq-version': '2015-06-06',
'content-type': 'text/xml;charset=utf-8',
'user-agent': 'mq-nodejs-sdk/1.0.4'
};
if (method !== 'GET' && method !== 'HEAD') {
const digest = kitx.md5(body, 'hex');
const md5 = Buffer.from(digest, 'utf8').toString('base64');
Object.assign(headers, {
'content-length': body.length,
'content-md5': md5
});
}
const signature = this.sign(method, headers, resource);
headers['authorization'] = `MQ ${this.accessKeyId}:${signature}`;
if (this.securityToken) {
headers['security-token'] = this.securityToken;
}
return headers;
}
/**
* 构造一个MQ的消费者
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
* @param {string} consumer 消费者名字
* @param {string} messageTag 消费的过滤标签,可空
*
* @returns {MQConsumer}
*/
getConsumer(instanceId, topic, consumer, messageTag) {
// eslint-disable-next-line no-use-before-define
return new MQConsumer(this, instanceId, topic, consumer, messageTag);
}
/**
* 构造一个MQ的生产者
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
*
* @returns {MQProducer}
*/
getProducer(instanceId, topic) {
// eslint-disable-next-line no-use-before-define
return new MQProducer(this, instanceId, topic);
}
/**
* 构造一个MQ的事务消息生产者
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
* @param {string} groupId 客户端GroupID
*
* @returns {MQTransProducer}
*/
getTransProducer(instanceId, topic, groupId) {
// eslint-disable-next-line no-use-before-define
return new MQTransProducer(this, instanceId, topic, groupId);
}
}
/**
* 消息属性
*/
class MessageProperties {
constructor() {
this.properties = {};
}
/**
* 获取消息属性内部的Object
*
* @returns {Object}
*/
getProperties() {
return this.properties;
}
/**
* 设置消息KEY
* @param {string} key 消息KEY
*/
messageKey(key) {
if (key == null) {
return;
}
this.properties["KEYS"] = key + "";
}
/**
* 定时消息,单位毫秒(ms),在指定时间戳(当前时间之后)进行投递。
* 如果被设置成当前时间戳之前的某个时刻,消息将立刻投递给消费者
*
* @param {Number} timeMillis 定时的绝对时间戳
*/
startDeliverTime(timeMillis) {
if (timeMillis == null) {
return;
}
this.properties["__STARTDELIVERTIME"] = timeMillis + "";
}
/**
* 在消息属性中添加第一次消息回查的最快时间,单位秒,并且表征这是一条事务消息
*
* @param {Number} timeSeconds 第一次消息回查时间,单位秒
*/
transCheckImmunityTime(timeSeconds) {
if (timeSeconds == null) {
return;
}
this.properties["__TransCheckT"] = timeSeconds + "";
}
/**
* 分区顺序消息中区分不同分区的关键字段,sharding key 于普通消息的 key 是完全不同的概念。
* 全局顺序消息,该字段可以设置为任意非空字符串。
*
* @param {string} key 分区键值
*/
shardingKey(key) {
if (key == null) {
return;
}
this.properties["__SHARDINGKEY"] = key + "";
}
/**
* 设置消息自定义属性
*
* @param {string} key 属性键,非空
* @param {string} value 属性值,非空
*/
putProperty(key, value) {
if (key == null || value == null) {
return;
}
const keyStr = key + "";
const valueStr = value + "";
if (keyStr != "" && valueStr != "") {
this.check(keyStr);
this.check(valueStr);
this.properties[keyStr] = valueStr;
}
}
check(key) {
if (key.indexOf('\'') > -1 || key.indexOf('"') > -1
|| key.indexOf('&') > -1 || key.indexOf('<') > -1
|| key.indexOf('>') > -1 || key.indexOf('|') > -1
|| key.indexOf(':') > -1) {
throw new Error(`Property ${key} can not contains: \" \' & < > | :`);
}
}
}
/**
* MQ的消息生产者
*/
class MQProducer {
/**
* 构造函数
* @param {MQClient} client MQ的客户端
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
*
* @returns {MQProducer}
*/
constructor(client, instanceId, topic) {
assert(client, '"client" must be passed in');
assert(topic, '"topic" must be passed in');
this.client = client;
this.instanceId = instanceId;
this.topic = topic;
if (instanceId && instanceId !== '') {
this.path = `/topics/${topic}/messages?ns=${instanceId}`;
} else {
this.path = `/topics/${topic}/messages`;
}
}
/**
* 向主题发送一条消息
* @param {string} body 发送的内容
* @param {string} tag 发送消息的标签
* @param {MessageProperties} msgProps 发送消息的属性
*
* @returns {object}
* ```json
* {
* // http请求状态码,发送成功就是201,如果发送失败则抛异常
* code: 201,
* // 请求ID
* requestId: "xxxxxxxxxxxxxx",
* // 发送消息的响应内容
* body: {
* // 消息ID
* MessageId: "",
* // 消息体内容的MD5值
* MessageBodyMD5: ""
* }
* }
* ```
* @throws {exception} err MQ服务端返回的错误或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,like: TopicNotExist
* Code:"",
* // 请求ID
* RequestId:""
* }
* ```
*/
async publishMessage(body, tag, msgProps) {
var xmlBody;
var params = {MessageBody: body};
if (tag && tag != '') {
params.MessageTag = tag;
}
if (msgProps) {
var props = msgProps.getProperties();
var propKeys = Object.keys(props);
if (propKeys.length > 0) {
params.Properties = propKeys
.map((key) => `${key}:${props[key]}`).join('|');
}
}
var response = this.client.post(this.path, 'Message', toXMLBuffer('Message', params));
return response;
}
}
/**
* MQ的消息生产者,支持事务
*/
class MQTransProducer {
/**
* 构造函数
* @param {MQClient} client MQ的客户端
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
* @param {string} groupId 客户端GroupID
*
* @returns {MQTransProducer}
*/
constructor(client, instanceId, topic, groupId) {
assert(client, '"client" must be passed in');
assert(topic, '"topic" must be passed in');
assert(groupId, '"groupId" must be passed in');
this.client = client;
this.instanceId = instanceId;
this.topic = topic;
this.groupId = groupId;
if (instanceId && instanceId !== '') {
this.path = `/topics/${topic}/messages?ns=${instanceId}`;
this.transPopPath = `/topics/${topic}/messages?consumer=${groupId}&ns=${instanceId}&trans=pop`;
this.transOprPath= `/topics/${topic}/messages?consumer=${groupId}&ns=${instanceId}`;
} else {
this.path = `/topics/${topic}/messages`;
this.transPopPath = `/topics/${topic}/messages?consumer=${groupId}&trans=pop`;
this.transOprPath= `/topics/${topic}/messages?consumer=${groupId}`;
}
}
/**
* 向主题发送一条消息
* @param {string} body 发送的内容
* @param {string} tag 发送消息的标签
* @param {MessageProperties} msgProps 发送消息的属性
*
* @returns {object}
* ```json
* {
* // http请求状态码,发送成功就是201,如果发送失败则抛异常
* code: 201,
* // 请求ID
* requestId: "xxxxxxxxxxxxxx",
* // 发送消息的响应内容
* body: {
* // 消息ID
* MessageId: "",
* // 消息体内容的MD5值
* MessageBodyMD5: ""
* // 消息句柄,仅事务消息存在
* ReceiptHandle: ""
* }
* }
* ```
* @throws {exception} err MQ服务端返回的错误或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,like: TopicNotExist
* Code:"",
* // 请求ID
* RequestId:""
* }
* ```
*/
async publishMessage(body, tag, msgProps) {
var xmlBody;
var params = {MessageBody: body};
if (tag && tag != '') {
params.MessageTag = tag;
}
if (msgProps) {
var props = msgProps.getProperties();
var propKeys = Object.keys(props);
if (propKeys.length > 0) {
params.Properties = propKeys
.map((key) => `${key}:${props[key]}`).join('|');
}
}
var response = this.client.post(this.path, 'Message', toXMLBuffer('Message', params));
return response;
}
/**
* 消费检查事务半消息,默认如果该条消息没有被 {commit} 或者 {rollback} 在NextConsumeTime时会再次消费到该条消息
*
* @param {int} numOfMessages 每次从服务端消费条消息
* @param {int} waitSeconds 长轮询的等待时间(可空),如果服务端没有消息请求会在该时间之后返回等于请求阻塞在服务端,如果期间有消息立刻返回
*
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "",
* body: [
* {
* // 消息ID
* MessageId: "",
* // 消息体MD5
* MessageBodyMD5: "",
* // 发送消息的时间戳,毫秒
* PublishTime: {long},
* // 下次重试消费的时间,前提是这次不调用{commit} 或者 {rollback},毫秒
* NextConsumeTime: {long},
* // 第一次消费的时间,毫秒,对于顺序消费无意义
* FirstConsumeTime: {long},
* // 消费的次数
* ConsumedTimes: {long},
* // 消息句柄,调用 {commit} 或者 {rollback} 需要将消息句柄传入,用于提交或者回滚该条事务消息
* ReceiptHandle: "",
* // 消息内容
* MessageBody: "",
* // 消息标签
* MessageTag: ""
* }
* ]
* }
*
* ```
* @throws {exception} err MQ服务端返回的错误或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,其中MessageNotExist是正常现象,表示没有可消费的消息
* Code: "",
* // 请求ID
* RequestId: ""
* }
* ```json
*/
async consumeHalfMessage(numOfMessages, waitSeconds) {
var url = this.transPopPath + `&numOfMessages=${numOfMessages}`;
if (waitSeconds) {
url += `&waitseconds=${waitSeconds}`;
}
const subType = 'Message';
var response = await this.client.get(url, 'Messages', {timeout: 33000});
response.body = response.body[subType];
response.body.forEach((msg) => {
processMsgProperties(msg);
});
return response;
}
/**
* 提交事务消息
*
* @param {string} receiptHandle consumeHalfMessage返回的单条消息句柄或者是发送事务消息返回的句柄
*
* @returns {object}
* ```json
* {
* // 请求成功
* code:204,
* // 请求ID
* requestId:""
* }
* ```
*
* @throws {exception} err 请求失败或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,如ReceiptHandleError,表示消息句柄非法,MessageNotExist如果超过了TransCheckImmunityTime(针对发送事务消息的句柄)或者超过NextCnosumeTime
* Code: ""
* // 请求ID
* RequestId: ""
* }
* ```
*/
async commit(receiptHandle) {
const body = toXMLBuffer('ReceiptHandles', [receiptHandle], 'ReceiptHandle');
const response = await this.client.delete(this.transOprPath + '&trans=commit', 'Errors', body);
// 3种情况,普通失败,部分失败,全部成功
if (response.body) {
const subType = 'Error';
// 部分失败
response.body = response.body[subType];
}
return response;
}
/**
* 回滚事务消息
*
* @param {string} receiptHandle consumeHalfMessage返回的单条消息句柄或者是发送事务消息返回的句柄
*
* @returns {object}
* ```json
* {
* // 请求成功
* code:204,
* // 请求ID
* requestId:""
* }
* ```
*
* @throws {exception} err 请求失败或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,如ReceiptHandleError,表示消息句柄非法,MessageNotExist如果超过了TransCheckImmunityTime(针对发送事务消息的句柄)或者超过NextCnosumeTime
* Code: ""
* // 请求ID
* RequestId: ""
* }
* ```
*/
async rollback(receiptHandle) {
const body = toXMLBuffer('ReceiptHandles', [receiptHandle], 'ReceiptHandle');
const response = await this.client.delete(this.transOprPath + '&trans=rollback', 'Errors', body);
// 3种情况,普通失败,部分失败,全部成功
if (response.body) {
const subType = 'Error';
// 部分失败
response.body = response.body[subType];
}
return response;
}
}
/**
* MQ的消息消费者
*/
class MQConsumer {
/**
* 消费者构造函数
* @param {MQClient} client MQ客户端
* @param {string} instanceId 实例ID
* @param {string} topic 主题名字
* @param {string} consumer 消费者名字(CID)a
* @param {string} messageTag 消费消息的过滤标签,可空
*
* @returns {MQConsumer}
*/
constructor(client, instanceId, topic, consumer, messageTag) {
assert(client, '"client" must be passed in');
assert(topic, '"topic" must be passed in');
assert(consumer, '"consumer" must be passed in');
this.client = client;
this.instanceId = instanceId;
this.topic = topic;
this.consumer = consumer;
if (messageTag) {
this.messageTag = encodeURIComponent(messageTag);
}
if (instanceId && instanceId !== '') {
if (this.messageTag) {
this.path = `/topics/${topic}/messages?consumer=${consumer}&ns=${instanceId}&tag=${this.messageTag}`;
} else {
this.path = `/topics/${topic}/messages?consumer=${consumer}&ns=${instanceId}`;
}
this.ackPath = `/topics/${topic}/messages?consumer=${consumer}&ns=${instanceId}`;
} else {
if (this.messageTag) {
this.path = `/topics/${topic}/messages?consumer=${consumer}&tag=${this.messageTag}`;
} else {
this.path = `/topics/${topic}/messages?consumer=${consumer}`;
}
this.ackPath = `/topics/${topic}/messages?consumer=${consumer}`;
}
}
/**
* 消费消息,默认如果该条消息没有被 {ackMessage} 确认消费成功,即在NextConsumeTime时会再次消费到该条消息
*
* @param {int} numOfMessages 每次从服务端消费条消息
* @param {int} waitSeconds 长轮询的等待时间(可空),如果服务端没有消息请求会在该时间之后返回等于请求阻塞在服务端,如果期间有消息立刻返回
*
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "",
* body: [
* {
* // 消息ID
* MessageId: "",
* // 消息体MD5
* MessageBodyMD5: "",
* // 发送消息的时间戳,毫秒
* PublishTime: {long},
* // 下次重试消费的时间,前提是这次不调用{ackMessage} 确认消费消费成功,毫秒
* NextConsumeTime: {long},
* // 第一次消费的时间,毫秒
* FirstConsumeTime: {long},
* // 消费的次数
* ConsumedTimes: {long},
* // 消息句柄,调用 {ackMessage} 需要将消息句柄传入,用于确认该条消息消费成功
* ReceiptHandle: "",
* // 消息内容
* MessageBody: "",
* // 消息标签
* MessageTag: ""
* }
* ]
* }
*
* ```
* @throws {exception} err MQ服务端返回的错误或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,其中MessageNotExist是正常现象,表示没有可消费的消息
* Code: "",
* // 请求ID
* RequestId: ""
* }
* ```json
*/
async consumeMessage(numOfMessages, waitSeconds) {
var url = this.path + `&numOfMessages=${numOfMessages}`;
if (waitSeconds) {
url += `&waitseconds=${waitSeconds}`;
}
const subType = 'Message';
var response = await this.client.get(url, 'Messages', {timeout: 33000});
response.body = response.body[subType];
response.body.forEach((msg) => {
processMsgProperties(msg);
});
return response;
}
/**
* 顺序消费消息,拿到的消息可能是多个分区的(对于分区顺序)一个分区的内的消息一定是顺序的
* 对于顺序消费,如果一个分区内的消息只要有没有被确认消费 {ackMessage} 成功,则对于这个分区在NextConsumeTime后还会消费到相同的消息
* 对于一个分区,只有所有消息确认消费成功才能消费下一批消息
*
* @param {int} numOfMessages 每次从服务端消费条消息
* @param {int} waitSeconds 长轮询的等待时间(可空),如果服务端没有消息请求会在该时间之后返回等于请求阻塞在服务端,如果期间有消息立刻返回
*
* @returns {object}
* ```json
* {
* code: 200,
* requestId: "",
* body: [
* {
* // 消息ID
* MessageId: "",
* // 消息体MD5
* MessageBodyMD5: "",
* // 发送消息的时间戳,毫秒
* PublishTime: {long},
* // 下次重试消费的时间,前提是这次不调用{ackMessage} 确认消费消费成功,毫秒
* NextConsumeTime: {long},
* // 第一次消费的时间,毫秒,顺序消费无意义
* FirstConsumeTime: {long},
* // 消费的次数
* ConsumedTimes: {long},
* // 消息句柄,调用 {ackMessage} 需要将消息句柄传入,用于确认该条消息消费成功
* ReceiptHandle: "",
* // 消息内容
* MessageBody: "",
* // 消息标签
* MessageTag: ""
* }
* ]
* }
*
* ```
* @throws {exception} err MQ服务端返回的错误或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,其中MessageNotExist是正常现象,表示没有可消费的消息
* Code: "",
* // 请求ID
* RequestId: ""
* }
* ```json
*/
async consumeMessageOrderly(numOfMessages, waitSeconds) {
var url = this.path + `&numOfMessages=${numOfMessages}`;
if (waitSeconds) {
url += `&waitseconds=${waitSeconds}`;
}
url += `&trans=order`;
const subType = 'Message';
var response = await this.client.get(url, 'Messages', {timeout: 33000});
response.body = response.body[subType];
response.body.forEach((msg) => {
processMsgProperties(msg);
});
return response;
}
/**
* 确认消息消费成功,消费成功后需要调用该接口否则会重复消费消息
*
* @param {array} receiptHandles 消息句柄数组
*
* @returns {object}
* ```json
* {
* // 请求成功
* code:204,
* // 请求ID
* requestId:""
* }
* ```
*
* @throws {exception} err 请求失败或者其它网络异常
* ```json
* {
* // MQ服务端返回的错误Code,如ReceiptHandleError,表示消息句柄非法,MessageNotExist表示超过了ack的时间,即NextConsumeTime
* Code: ""
* // 请求ID
* RequestId: ""
* }
* ```
*/
async ackMessage(receiptHandles) {
const body = toXMLBuffer('ReceiptHandles', receiptHandles, 'ReceiptHandle');
const response = await this.client.delete(this.ackPath, 'Errors', body);
// 3种情况,普通失败,部分失败,全部成功
if (response.body) {
const subType = 'Error';
// 部分失败
response.body = response.body[subType];
}
return response;
}
}
module.exports = {
MQClient,
MQConsumer,
MQProducer,
MessageProperties
};
</pre>
</article>
</section>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="modal fade" id="searchResults">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Search results</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<footer>
<span class="copyright">
MIT
</span>
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.7</a>
on Wed Nov 17th 2021
using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>