工具类
- [实现目标 - 简介](#实现目标 - 简介)
- 环境
-
- [npm / pnpm](#npm / pnpm)
- 代码实现
- [Producer / Consumer 目录结构](#Producer / Consumer 目录结构)
-
-
- [Producer 文件目录](#Producer 文件目录)
- [Consumer 文件目录](#Consumer 文件目录)
- 使用示例
-
实现目标 - 简介
最大程度简化 rocketmq-client-nodejs 客户端收发消息的使用方式,以傻瓜式写法 topic.tag(message) 即可实现消息收发功能。
支持多集群连接。
集群部署模式,推荐:NameServer+Controller × 3, Proxy × 2, Broker × 2。可选:可视化 RMQ-Studio。
环境
Node.js v22+
Express / Koa / ...等,后端服务实现
引入第三方库:
"rocketmq-client-nodejs": "^1.1.0"
npm / pnpm
执行
pnpm install rocketmq-client-nodejs
package.json
json
{
"dependencies": {
"rocketmq-client-nodejs": "^1.1.0"
}
}
代码实现
Client.js - 基础工具类
js
const MQ = require('rocketmq-client-nodejs');
const { log } = require('../log'); // 自行引入日志框架或console
const isObj = o => Object.prototype.toString.call(o) === '[object Object]';
/**
* "驼峰式"转"_式"
*/
function HumpTo_(str) {
if (!str?.length)
return str;
return [ ...str.toString() ]
.map(c => c >= 'A' && c <= 'Z' ? `_${c.toLowerCase()}` : c)
.join('');
}
/**
* 生产客户端
*/
class Producer {
/**
* 配置
*/
#option;
/**
* 实例
*/
#I;
/**
* 启动完成事件
*/
#startup;
constructor({ logger = log, ...option }) {
this.#option = option;
option.logger = logger;
tr: try {
let { TransactionResolution } = require('rocketmq-client-nodejs/proto/apache/rocketmq/v2/definition_pb');
log.debug('RMQ: TransactionResolution 枚举加载成功,事务消息可用');
if (option.checker?.check) {
break tr;
}
option.checker = {
async check({ body, ...mv }) {
log.warn('RMQ: 事务回查 > 回滚', mv);
return TransactionResolution.ROLLBACK;
},
};
} catch (e) {
option.checker = undefined;
log.warn('RMQ: TransactionResolution 枚举未能加载,事务消息不可用', e);
}
log.debug('RMQ: Producer 配置参数', this.#option);
}
get option() {
return this.#option;
}
get I() {
return this.#startup;
}
/**
* 初始化
* @return {Promise<MQ#Producer>}
*/
init() {
if (this.#startup) {
log.debug('RMQ: Producer already running. 生产客户端已启动,无需重复启动 %s %s', this.option.endpoints, this.option.topics);
return this.#startup;
}
if (this.#I) {
return Promise.reject('Producer正在关闭中');
}
this.#I = new MQ.Producer(this.option);
this.#startup = this.#I.startup()
.then(() => {
log.mark('RMQ: Producer start. 生产客户端初始化启动成功 %s %s', this.option.endpoints, this.option.topics);
return this.#I;
})
.catch(e => {
this.#I = null;
this.#startup = null;
log.error('RMQ: Producer startup failed. 生产客户端初始化启动失败 %s %s', this.option.endpoints, this.option.topics, e);
return Promise.reject(e);
});
return this.#startup;
}
/**
* 发送消息
* @param msg {MQ#Message}
* @param args {object} 其它参数
* @return {Promise<MQ#SendReceipt>}
*/
send(msg, ...args) {
msg.body = Producer.bodyOf(msg.body);
let message = new MQ.Message(msg);
return this.#startup.then(I => I.send(message, ...args))
.catch(e => (log.error('RMQ: Producer send failed. 生产客户端发送消息失败 %s %s', this.option.endpoints, this.option.topics, e), e));
}
/**
* 批量发送消息
* @param msgs {MQ#Message[]}
* @return {Promise<[MQ#SendReceipt|null]>} 失败位填充 null。
*/
sendBatch(msgs = []) {
if (!msgs.length) {
return Promise.resolve([]);
}
return Promise.allSettled(msgs.map(m => this.send(m)))
.then(rs => rs.map(r => (r.status === 'fulfilled' ? r.value : null)));
}
/**
* 普通消息
* @see {@link #send}
*/
normal() {
return this.send(...arguments);
}
/**
* 延迟消息
* @param msg {MQ#Message}
* @param msg.delay {number} 延迟时间
* @param delay {number} 同 msg.delay
* @return {Promise<MQ#SendReceipt>}
*/
delay(msg, delay) {
msg.delay ??= delay;
return this.send(msg)
.then(receipt => {
receipt.recall = () => this.#startup // 撤回方法(仅"消费之前"有效)
.then(I => I.recallMessage(msg.topic, receipt.recallHandle))
.then(re => {
log.info('RMQ: 延时消息已撤回,原消息ID=%s,撤回结果=%s', receipt.messageId, re);
return re;
})
.catch(e => (log.error('RMQ: 延时消息撤回异常,原消息ID=%s', receipt.messageId, e), e));
return receipt;
});
}
/**
* 顺序消息 - FIFO
* @param msg {MQ#Message}
* @param group {string} 消息分组(messageGroup),同组内严格有序;
* @return {Promise<MQ#SendReceipt>}
*/
fifo(msg, group) {
msg.messageGroup ??= group ?? msg.group;
if (!msg.messageGroup) {
return Promise.reject(new Error('顺序消息必须指定分组(或Topic)'));
}
return this.send(msg);
}
/**
* 事务消息
* @param msg {MQ#Message}
* @param run {Function} 事务执行函数,正常return则提交,throw则回滚
* @return {Promise<MQ#SendReceipt>}
*/
transaction(msg, run) {
if (!this.#option.checker?.check) {
throw new Error('不支持事务消息,需RocketMQ V5.5.0及以上版本支持');
}
const tx = this.#I.beginTransaction();
let err = (e, receipt) => {
return tx.rollback()
.then(() => log.error('RMQ: 事务消息执行异常,已回滚', receipt, e))
.catch(e0 => log.error('RMQ: 事务消息自身回滚异常', receipt, e0, e))
.then(() => Promise.reject(e));
};
let receipt;
try {
return this.send(msg, tx)
.then(r => (receipt = r, run ? run(r) : r))
.then(r => tx.commit()
.then(() => r)
.catch(e => err(e, r))
)
.catch(e => err(e, receipt));
} catch (e) {
return err(e, receipt);
}
}
/**
* 关闭客户端
* @return {Promise<boolean>}
*/
close() {
let startup = this.#startup;
if (!startup) {
return Promise.resolve(true);
}
this.#startup = null;
return startup.then(I => I?.shutdown())
.then(() => {
this.#I = null;
log.mark('RMQ: Producer shutdown. 生产客户端已关闭 %s %s', this.option.endpoints, this.option.topics);
return true;
})
.catch(e => {
this.#startup = startup; // 关闭失败则恢复
log.error('RMQ: Producer shutdown failed. 生产客户端关闭失败 %s %s', this.option.endpoints, this.option.topics, e);
return false;
});
}
/**
* 转换消息体
* @param body {string | object | Buffer}
* @return {Buffer}
*/
static bodyOf(body) {
if (body == null)
return Buffer.from('');
if (Buffer.isBuffer(body))
return body;
if (typeof body === 'object')
body = JSON.stringify(body);
return Buffer.from(body, 'utf8');
}
}
/**
* 消费客户端
*/
class Consumer {
/**
* 消费处理函数
*/
#handler;
/**
* 消息格式化函数
*/
#fmtMv = (mv) => Consumer.fmtMv(mv);
/**
* 配置参数
*/
#option;
/**
* 消费组内Topic
* @type {{string:Group}}
*/
#topics;
/**
* 实例
*/
#I;
/**
* 启动完成事件
*/
#startup;
/**
* PushConsumer相关参数
*/
constructor({ handler, fmtMv, topics, group, logger = log, ...opt }) {
opt.consumerGroup ??= group;
if (isObj(opt.consumerGroup)) {
opt.consumerGroup = Object.keys(opt.consumerGroup)[ 0 ];
}
if (opt.consumerGroup == null) {
throw new Error('必须指定消费组');
}
this.handler = handler;
this.fmtMv = fmtMv;
opt.logger = logger;
opt.subscriptions = Consumer.subsOf(topics);
this.#option = opt;
this.#topics = topics;
}
get group() {
return this.#option.consumerGroup;
}
get option() {
return this.#option;
}
get I() {
return this.#startup;
}
set handler(fn) {
if (fn == null) {
this.#handler = undefined;
return;
}
if (typeof fn == 'function') {
this.#handler = fn;
return;
}
throw new Error('消费处理器必须为函数');
}
set fmtMv(fn) {
if (fn == null) {
return;
}
if (typeof fn == 'function') {
this.#fmtMv = fn;
return;
}
throw new Error('消息格式化必须为函数');
}
/**
* 初始化
*/
init({ handler, fmtMv } = {}) {
if (this.#startup) {
log.info('RMQ: PushConsumer already running [%s]. 消费客户端已启动,无需重复启动 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return this.#startup;
}
if (this.#I) {
return Promise.reject('PushConsumer正在关闭中');
}
fmtMv != null && (this.fmtMv = fmtMv);
handler != null && (this.handler = handler);
this.#I = new MQ.PushConsumer({
...this.#option,
messageListener: {
consume: mv => this.consume(mv)
}
});
this.#startup = this.#I.startup()
.then(() => {
log.mark('RMQ: PushConsumer start [%s]. 消费客户端初始化启动成功 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return this.#I;
})
.catch(e => {
this.#I = null;
this.#startup = null;
log.error('RMQ: PushConsumer startup failed [%s]. 消费客户端初始化启动失败 %s %s', this.group, this.option.endpoints, this.option.subscriptions, e);
return Promise.reject(e);
});
return this.#startup;
}
/**
* 订阅/自动消费
* @return {Promise<MQ#ConsumeResult>} 正常return则自动ACK,throw则自动重试。
*/
async consume(mv) {
let g = this.#topics[ mv.topic ];
if (!g) {
var fmtMv = this.#fmtMv;
var h = this.#handler;
} else {
var fmtMv = (typeof g.fmtMv == 'function') ? g.fmtMv.bind(g) : this.#fmtMv; // 关键:使用bind还给原实例
var h = g[ mv.tag ] || g.handler;
h = (typeof h == 'function') ? h.bind(g) : this.#handler; // 允许退化为默认处理器
}
try {
fmtMv && (mv = fmtMv(mv));
if (!h) {
log.warn('RMQ: PushConsumer [%s] 未设置消费处理器,直接ACK失败。消息: %s', this.group, JSON.stringify(mv));
return MQ.ConsumeResult.FAILURE;
}
let r = h(mv);
if (!r || typeof r.then != 'function') {
r = Promise.resolve(r);
}
return r.then(v => v instanceof MQ.ConsumeResult ? v : MQ.ConsumeResult.SUCCESS)
.catch(e => {
log.error('RMQ: PushConsumer [%s] 消费失败,ACK失败。消息: %s', this.group, JSON.stringify(mv), e);
return MQ.ConsumeResult.FAILURE;
});
} catch (e) {
log.error('RMQ: PushConsumer [%s] 消费异常,ACK失败。消息: %s', this.group, JSON.stringify(mv), e);
return MQ.ConsumeResult.FAILURE;
}
}
/**
* 关闭客户端
* @return {Promise<boolean>}
*/
close() {
let startup = this.#startup;
if (!startup) {
return Promise.resolve(true);
}
this.#startup = null;
return startup.then(I => I?.shutdown())
.then(() => {
this.#I = null;
log.mark('RMQ: PushConsumer shutdown [%s]. 消费客户端已关闭 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return true;
})
.catch(e => {
this.#startup = startup; // 关闭失败则恢复
log.error('RMQ: PushConsumer shutdown failed [%s]. 消费客户端关闭失败 %s %s', this.group, this.option.endpoints, this.option.subscriptions, e);
return false;
});
}
/**
* 消息格式化函数
*/
static fmtMv(mv) {
let body = mv[ '#body' ] = mv.body;
if (Buffer.isBuffer(body)) {
body = mv.body = body.toString('utf8');
}
if (typeof body != 'string') {
return mv;
}
if ((body.startsWith('{') && body.endsWith('}')) || (body.startsWith('[') && body.endsWith(']')) || (body.startsWith('"') && body.endsWith('"'))) {
try {
body = mv.body = JSON.parse(body);
} catch (e) {
log.info('RMQ: 消息体尝试解析为JSON失败 [%s, %s, %s] - %s', mv.messageId, mv.topic, mv.tag, body, e);
}
}
return mv;
}
/**
* 转换为subscriptions格式
* @param topics {string[][] | {string:Topic}}
* @return {Map<string,string>}
*/
static subsOf(topics) {
if (Array.isArray(topics)) {
var tps = topics;
} else {
var tps = Object.entries(topics)
.map(([ k, v ]) => {
let tag = v.tags?.length ?
v.tags.filter(Boolean).join('||') :
(v.tag ?? v);
return [ k, tag ];
});
}
return new Map(tps);
}
}
/**
* 自定义消费客户端
*/
class SimpleConsumer {
/**
* 消费处理函数
*/
#handler;
/**
* 消息格式化函数
*/
#fmtMv = (mv) => Consumer.fmtMv(mv);
/**
* 配置参数
*/
#option;
/**
* 消费组内Topic
* @type {{string:Group}}
*/
#topics;
/**
* 实例
*/
#I;
/**
* 启动完成事件
*/
#startup;/**
* SimpleConsumer相关参数
*/
constructor({ handler, fmtMv, topics, group, logger = log, ...opt }) {
opt.consumerGroup ??= group;
if (isObj(opt.consumerGroup)) {
opt.consumerGroup = Object.keys(opt.consumerGroup)[ 0 ];
}
if (opt.consumerGroup == null) {
throw new Error('必须指定消费组');
}
this.handler = handler;
this.fmtMv = fmtMv;
opt.logger = logger;
opt.subscriptions = Consumer.subsOf(topics);
this.#option = opt;
this.#topics = topics;
}
get group() {
return this.#option.consumerGroup;
}
get option() {
return this.#option;
}
get I() {
return this.#startup;
}
set handler(fn) {
if (fn == null) {
this.#handler = undefined;
return;
}
if (typeof fn == 'function') {
this.#handler = fn;
return;
}
throw new Error('消费处理器必须为函数');
}
set fmtMv(fn) {
if (fn == null) {
return;
}
if (typeof fn == 'function') {
this.#fmtMv = fn;
return;
}
throw new Error('消息格式化必须为函数');
}
/**
* 初始化
*/
init({ handler, fmtMv } = {}) {
if (this.#startup) {
log.info('RMQ: SimpleConsumer already running [%s]. 基础消费客户端已启动,无需重复启动 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return this.#startup;
}
if (this.#I) {
return Promise.reject('SimpleConsumer正在关闭中');
}
fmtMv != null && (this.fmtMv = fmtMv);
handler != null && (this.handler = handler);
this.#I = new MQ.SimpleConsumer(this.#option);
this.#startup = this.#I.startup()
.then(() => {
log.mark('RMQ: SimpleConsumer start [%s]. 基础消费客户端初始化启动成功 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return this.#I;
})
.catch(e => {
this.#I = null;
this.#startup = null;
log.error('RMQ: SimpleConsumer startup failed [%s]. 基础消费客户端初始化启动失败 %s %s', this.group, this.option.endpoints, this.option.subscriptions, e);
return Promise.reject(e);
});
return this.#startup;
}
/**
* 拉取一批消息(由调用方触发)
* @param tag {string} 消息标签。若有,则只拉取该标签的消息。
* @param limit {number} 拉取数量
* @param duration {number} (毫秒)消息不可见时长。拉取后在该时长内对其他消费者不可见,服务端要求最小 10000ms。
* @return {Promise<void>}
*/
pull({ tag, limit, duration }) {
duration = SimpleConsumer.#rectifyDuration(duration)
return this.#startup.then(I => I.receive(limit, duration))
.then((mvs = []) => {
let prms = mvs.filter(mv => tag == null || mv.tag === tag)
.map(mv => this.consume(mv).then(r => {
if (r !== MQ.ConsumeResult.SUCCESS) {
return false;
}
return this.#I.ack(mv)
.then(() => true)
.catch(e => (log.error('RMQ: SimpleConsumer [%s] ACK确认异常。消息: %s', this.group, JSON.stringify(mv), e), false));
}));
return Promise.allSettled(prms);
})
.then(rs =>
rs.reduce((pre, im) => {
if (im.status === 'rejected') {
pre.e++;
} else if (im.status === 'fulfilled') {
im.value ? pre.y++ : pre.n++;
}
return pre;
}, { y: 0, n: 0, e: 0, length: rs.length })
);
}
/**
* 订阅/消费
* @return {Promise<MQ#ConsumeResult>} 正常return则自动ACK,throw则自动重试。
*/
async consume(mv) {
let g = this.#topics[ mv.topic ];
if (!g) {
var fmtMv = this.#fmtMv;
var h = this.#handler;
} else {
var fmtMv = (typeof g.fmtMv == 'function') ? g.fmtMv.bind(g) : this.#fmtMv; // 关键:使用bind还给原实例
var h = g[ mv.tag ] || g.handler;
h = (typeof h == 'function') ? h.bind(g) : this.#handler; // 允许退化为默认处理器
}
try {
fmtMv && (mv = fmtMv(mv));
if (!h) {
log.warn('RMQ: SimpleConsumer [%s] 未设置消费处理器,直接ACK失败。消息: %s', this.group, JSON.stringify(mv));
return MQ.ConsumeResult.FAILURE;
}
let r = h(mv);
if (!r || typeof r.then != 'function') {
r = Promise.resolve(r);
}
return r.then(v => v instanceof MQ.ConsumeResult ? v : MQ.ConsumeResult.SUCCESS)
.catch(e => {
log.error('RMQ: SimpleConsumer [%s] 消费失败,ACK失败。消息: %s', this.group, JSON.stringify(mv), e);
return MQ.ConsumeResult.FAILURE;
});
} catch (e) {
log.error('RMQ: SimpleConsumer [%s] 消费异常,ACK失败。消息: %s', this.group, JSON.stringify(mv), e);
return MQ.ConsumeResult.FAILURE;
}
}
/**
* 关闭客户端
* @return {Promise<boolean>}
*/
close() {
let startup = this.#startup;
if (!startup) {
return Promise.resolve(true);
}
this.#startup = null;
return startup.then(I => I?.shutdown())
.then(() => {
this.#I = null;
log.mark('RMQ: SimpleConsumer shutdown [%s]. 基础消费客户端已关闭 %s %s', this.group, this.option.endpoints, this.option.subscriptions);
return true;
})
.catch(e => {
this.#startup = startup; // 关闭失败则恢复
log.error('RMQ: SimpleConsumer shutdown failed [%s]. 基础消费客户端关闭失败 %s %s', this.group, this.option.endpoints, this.option.subscriptions, e);
return false;
});
}
/**
* 常量 - 消息不可见时长。拉取后在该时长内对其他消费者不可见,服务端要求最小 10000ms。
* @return {number} 10000
*/
static get invisibleDuration() {
return 10000;
}
/**
* 矫正不可见时长。确保其不低于 {@link SimpleConsumer#invisibleDuration}
* @return {number} {@param duration} | {@link SimpleConsumer#invisibleDuration}
*/
static #rectifyDuration(duration) {
duration = +duration;
return !duration ? SimpleConsumer.invisibleDuration : Math.max(duration, SimpleConsumer.invisibleDuration);
}
}
/**
* Topic接口
*/
class Topic {
#topic;
tag;
tags;
constructor({ topic, tag, tags, pre = '' } = {}) {
if (topic == null) {
let name = this.constructor.name;
name = name.charAt(0).toLowerCase() + name.slice(1);
topic = HumpTo_(name);
}
this.#topic = pre + topic.toString();
this.tag = tag;
this.tags = tags?.length ? tags : Topic.#tagsOf(this);
this instanceof Group || log.debug('MQ.Topic: 已注册[%s, %s]', this.topic, this.tag);
}
get topic() {
return this.#topic;
}
/**
* 常量TAG
*/
static get TAG() {
return '*';
}
/**
* Consumer 消费处理器(Group > Topic级)
*/
handler(mv) {
log.debug('MQ.Group.Topic: {group: %s, topic: %s, tag: %s} 处理消息 %s', this.group, this.topic, this.tag, mv);
}
/**
* 消息格式化函数
*/
fmtMv(mv) {
return Consumer.fmtMv(mv);
}
toJSON() {
return { topic: this.#topic, tag: this.tag, tags: this.tags };
}
/**
* 获取所有方法名
* @return {string[]}
*/
static #tagsOf(I) {
const tags = new Set();
let proto = Object.getPrototypeOf(I);
while (proto && proto !== Group.prototype && proto !== Topic.prototype) {
let ks = Object.getOwnPropertyNames(proto);
for (const k of ks) {
if (typeof k != 'string' || k.startsWith('_') || k.startsWith('#') || k === 'constructor') {
continue;
}
const d = Object.getOwnPropertyDescriptor(proto, k);
if (!d || typeof d.value !== 'function') {
continue;
}
tags.add(k);
}
proto = Object.getPrototypeOf(proto);
}
return Array.from(tags);
}
}
/**
* 消费组接口
*/
class Group extends Topic {
#group;
constructor({ group = '', groupPre = '', topic, tag, pre }) {
super({ topic, tag, pre });
this.#group = groupPre + group;
log.debug('MQ.Group.Topic: 已注册[%s, %s, %s]', this.group, this.topic, this.tag);
}
get group() {
return this.#group;
}
toJSON() {
return { group: this.#group, topic: this.topic, tag: this.tag, tags: this.tags };
}
}
/**
* 自动发送客户端
*/
class AutoTopic extends Topic {
/**
* 客户端
*/
client;
constructor(arg) {
super(arg);
Object.defineProperty(this, 'client', {
value: arg.client,
writable: true,
enumerable: false,
configurable: true,
});
return AutoTopic.auto(this);
}
/**
* 自动发送
* @param I {AutoTopic} this
* @return {Proxy<AutoTopic>} I
*/
static auto(I) {
let doTag = (msg, tag) => {
if (isObj(msg) && 'body' in msg) {
msg.tag ??= tag; // 设置tag
return msg;
}
return { body: msg, tag }; // 约定:第一个参数是Message
};
let prx = new Proxy(I, {
get: (target, prop, receiver) => {
const own = Reflect.get(target, prop);
if (typeof own != 'function') {
return own;
}
if (typeof prop != 'string' || prop.startsWith('_') || prop.startsWith('#') || !target.tags.includes(prop)) {
return own.bind(target);
}
return (msg, ...args) => {
msg = doTag(msg, prop);
let send = target.client.send;
let idx = target.topic.lastIndexOf('_');
if (idx >= 0) {
let type = target.topic.substring(idx + 1).toLowerCase(); // 截取尾缀,作为Topic消息类型
send = target.client[ type ];
if (send) {
AutoTopic.#supplArg({ type, target }, msg, args);
} else {
send = target.client.send; // 退化为Producer.send()
}
}
let prm = send(msg, ...args);
let apply = r => own.apply(target, [ r, msg, ...args ]); // 约定第一个参数为发送结果SendReceipt 或 异常Error
return (prm instanceof Promise ? prm : Promise.resolve(prm))
.then(
apply,
e => (log.error('MQ: AutoTopic [%s, %s] 自动发送消息失败 %s', target.topic, prop, JSON.stringify(msg), e), apply(e))
)
.catch(e => log.error('MQ: AutoTopic [%s, %s] 自动发送消息处理异常 %s', target.topic, prop, JSON.stringify(msg), e));
};
}
});
Object.setPrototypeOf(prx, Object.getPrototypeOf(I));
return prx;
}
/**
* 补充参数
* @param type {string} 消息类型
* @param target {AutoTopic}
* @param msg {MQ#Message} 消息
* @param args {Array} 参数列表
*/
static #supplArg({ type, target }, msg, args) {
switch (type) {
case 'delay': {
if (+args[ 0 ] >= 0 || msg.delay >= 0) {
break;
}
if (target.delay == null) {
let ns = target.topic.split('_'); // Topic命名约定:前缀_时长+单位_delay。例如:tp_1d_delay 表示延时1天。
target.delay = 1;
for (let i = ns.length - 2; i >= 0; i--) {
let n = ns[ i ];
if (n.length < '1D'.length) {
continue;
}
let ce = n.charAt(n.length - 1).toLowerCase();
if (![ 's', 'm', 'h', 'd', 'w', 'y' ].some(c => ce === c)) { // 判断是否为时间单位
continue;
}
if (![ ...n ].some(c => c >= '0' && c <= '9')) {
continue;
}
try { // 也可采用dayjs的'dayjs/plugin/duration'表达式解析。全局注册:dayjs.extend(require('dayjs/plugin/duration'));
let time = n.slice(0, n.length - 1);
switch (ce) {
case 'w': time *= 7; // 周
case 'd': time *= 24; // 天
case 'h': time *= 60; // 时
case 'm': time *= 60; // 分
case 's': {} // 秒
default: time *= 1000;
}
target.delay = time; // 毫秒
break;
} catch (e) {}
}
}
msg.delay = target.delay;
break;
}
case 'fifo': {
if (args[ 0 ] != null || msg.group != null || msg.messageGroup != null) {
break;
}
target.group != null && (msg.group = target.group);
break;
}
}
return msg;
}
}
/**
* RocketMQ
*/
module.exports = {
Producer,
Consumer,
SimpleConsumer,
Topic,
Group,
AutoTopic,
isObj,
HumpTo_,
};
RocketMQ.js - 配置加载
js
const { Producer, Consumer, Topic, Group, AutoTopic, HumpTo_, isObj } = require('./Client');
const Interceptors = require('./Interceptor'); // 消息拦截器
const { log } = require('../log'); // 自行引入日志框架
/**
* MQ配置
* @description 可通过process.env自行添加/获取配置。
* @type {{}} 相关配置属性,可通过查阅 {@link Producer} 和 {@link Consumer} 获取详细信息。
*/
const mq = {
"async": { // 自定义的集群名称
"conn": { // 连接池
"endpoints": "192.168.0.1:10811", // Proxy代理服务地址
"namespace": "",
"requestTimeout": 8000,
"sessionCredentials": { "accessKey": "login_name", "accessSecret": "password" },
"sslEnabled": false
},
"producer": { // 生产者 {@link MQ.Producer}
"maxAttempts": 3,
"messageInterceptor": [ "SendLog" ] // 设置加载哪些日志拦截器,名称参见 {@link Interceptors} 导出类名
},
"consumer": { // 消费者 {@link MQ.Consumer}
"enableFifoConsumeAccelerator": false,
"longPollingTimeout": 20000,
"maxCacheMessageCount": 1000,
"maxCacheMessageSizeInBytes": 67108864,
"messageInterceptor": [ "RecvLog" ] // 设置加载哪些日志拦截器,名称参见 {@link Interceptors} 导出类名
},
"setting": {
"topic": { "pre": "tp_" }, // Topic命名前缀。指定以"tp_"开头,结尾必须指定Topic消息类型
"group": { "pre": "g_" }, // ConsumerGroup命名前缀。指定以"g_"开头
"intercept": { "logLevel": "info" }, // message拦截器日志级别
"start": true, // 是否随项目启动,同时加载启动客户端
/**
* 自动扫描目录,指定MQ客户端Topic/Group的加载目录。
* 规约:
* - 为字符串类型时:自动查找该目录下 "/producer/"和"/consumer/组名下划线分隔对应多级文件夹名" 目录,分别加载 Topic 和 Group;
* - 为对象类型时:分别指定 { "pBaseUrl": "producer目录", "cBaseUrl": "consumer目录" };
*/
"scan": "/src/main/js/com/x/x/mq/async"
}
},
"sync": {} // 自定义的集群名称-2,同async
};
if (!mq) {
throw new Error('MQ not config 未配置');
}
if (mq.uri && mq.endpoints) {
var cfgs = { '': mq };
} else if (Array.isArray(mq)) {
var cfgs = { ...mq };
} else if (mq instanceof Object) {
var cfgs = mq;
} else {
throw new Error('MQ 配置错误');
}
/**
* RocketMQ客户端
*/
class RMQ {
/**
* 生产客户端实例
*/
#producer;
/**
* 生产者 - Topic
*/
#produce;
/**
* 消费客户端实例
*/
#consumer;
constructor({ conn, producer, consumer, setting = {} }) {
if (setting.scan) {
var { producer: topics, consumer: groups } = RMQ.#scan(setting);
if (log.isInfoEnabled()) {
log.info('RMQ: 扫描到\r\n\tProducer.topics [%s]\r\n\tConsumer.group [%s]', JSON.stringify(topics), JSON.stringify(groups));
}
}
if (producer) {
this.#initProducer({ producer, conn, setting, topics });
}
if (consumer) {
this.#initConsumer({ consumer, conn, setting, groups });
}
}
/**
* 生产客户端
*/
get producer() {
return this.#producer;
}
/**
* 消费客户端
*/
get consumer() {
return this.#consumer;
}
/**
* 生产者 - Topic
*/
getProduce() {
return this.#produce;
}
group(k) {
return this.#consumer[ k ];
}
#initProducer({ producer, conn, topics = [], setting }) {
producer.topics = topics.map(im => im.topic);
let messageInterceptor = RMQ.#intercepts(producer.messageInterceptor, { conn, setting });
let opt = Object.assign({}, producer, conn, { messageInterceptor });
let produce = new Producer(opt);
this.#producer = RMQ.#handInit(produce); // 第二层代理:方法调用前先init(),并把this固定到真实实例
setting.start && producer.topics.length && this.#producer.init();
let setTopic = (arg, topic) => {
if (arg == null || !isObj(arg)) {
return;
}
if (Array.isArray(arg)) { // 批量消息逐个设置
return arg.forEach(im => im && ('body' in im) && setTopic(im, topic)); // 任意参数必须是Message
}
'body' in arg && (arg.topic = topic); // 约定:第一个参数是Message
};
this.#produce = topics
.reduce((pre, im) => {
let { topic } = im;
let client = new Proxy(this.#producer, {
get(target, prop) {
const own = target[ prop ]; // 经#handInit:已处理init拦截,方法this已绑定真实实例
if (typeof own != 'function') { // 非方法属性(option/topics等)直接透传
return own;
}
if (RMQ.#ignoFn(prop)) {
return own;
}
return (...args) => {
setTopic(args[ 0 ], topic);
return own(...args); // 不能再用target作this:它是代理,访问私有字段会抛错
};
}
});
im instanceof AutoTopic && (im.client = client);
pre[ topic ] = client;
return pre;
}, Object.create(null));
return this.#producer;
}
#initConsumer({ consumer, conn, groups, setting }) {
let messageInterceptor = RMQ.#intercepts(consumer.messageInterceptor, { conn, setting });
let opt = Object.assign({}, consumer, conn, { messageInterceptor });
this.#consumer = Object.entries(groups)
.reduce((pre, [ group, topics ]) => {
let consume = new Consumer({ ...opt, group, topics });
pre[ group ] = RMQ.#handInit(consume);
setting.start && pre[ group ].init();
return pre;
}, Object.create(null));
return this.#consumer;
}
/**
* AOP拦截 - 初始化处理
* @param target {Object} 目标对象
* @return {*|(function(...[*]): *)}
*/
static #handInit(target) {
return new Proxy(target, {
get(target, prop) {
const own = Reflect.get(target, prop);
if (typeof own != 'function') {
return own;
}
if (RMQ.#ignoFn(prop)) { // init/close必须绑定真实实例
return own.bind(target);
}
let f = (...args) => own.apply(target, args);
if (!target.I) { // 未初始化:先init,再用原始参数调用(init结果不能当参数)
return (...args) => target.init()
.then(() => f(...args));
}
return f;
}
});
}
static #ignoFn(prop) {
return typeof prop != 'string' || [ 'init', 'close' ].includes(prop) || prop.startsWith('#');
}
/**
* 扫描指定路径下的Producer/Consumer
*/
static #scan({ scan, topic: { pre }, group: { pre: groupPre } }) {
const FS = require('fs');
const Path = require('path');
const cwd = process.cwd();
if (typeof scan == 'string') {
let url = scan.endsWith('/') ? scan : scan + '/';
scan = {
pBaseUrl: url + 'producer',
cBaseUrl: url + 'consumer'
};
}
scan.pBaseUrl = paserUrl(scan.pBaseUrl);
scan.cBaseUrl = paserUrl(scan.cBaseUrl);
let pjs = findJs(scan.pBaseUrl);
let cjs = findJs(scan.cBaseUrl);
return {
producer: scanProducer(scan.pBaseUrl, pjs),
consumer: scanConsumer(scan.cBaseUrl, cjs),
};
function scanProducer(baseDir, files) {
return files.map(im => {
let mod = require(im);
let file = Path.basename(im, Path.extname(im)); // 文件名即为class类名
let Producer = mod[ file ] ?? mod.default ?? mod;
if (typeof Producer != 'function') {
return;
}
let producer = new Producer({ pre });
if (!(producer instanceof Topic)) {
return;
}
let I = file.charAt(0).toLowerCase() + file.slice(1);
mod[ I ] ??= producer;
mod.I ??= producer;
return producer;
})
.filter(Boolean);
}
function scanConsumer(baseDir, files) {
return files.reduce((r, im) => {
let mod = require(im);
let file = Path.basename(im, Path.extname(im)); // 文件名即为class类名
let Consumer = mod[ file ] ?? mod.default ?? mod;
if (typeof Consumer != 'function') {
return r;
}
let rel = Path.relative(baseDir, Path.dirname(im)); // 中间路径段,定义为group
let group = rel ? rel.split(Path.sep).filter(Boolean).join('_') : HumpTo_(Consumer.name);
let consumer = new Consumer({ group, pre, groupPre: group ? groupPre : undefined });
if (consumer instanceof Group) {
if (r[ consumer.group ] == null) {
r[ consumer.group ] = Object.create(null);
}
r[ consumer.group ][ consumer.topic ] = consumer;
let I = file.charAt(0).toLowerCase() + file.slice(1);
mod[ I ] ??= consumer;
mod.I ??= consumer;
}
return r;
}, Object.create(null));
}
/**
* 递归扫描目录下所有.js文件
* @param dir {string|Object} 目录路径
* @return {string[]} 绝对路径组
*/
function findJs(dir) {
let rs = [];
if (!FS.existsSync(dir)) {
log.error('RMQ: 扫描目录不存在,请检查[%s]', dir);
return rs;
}
const fds = FS.readdirSync(dir);
fds.forEach(file => {
const fdir = Path.join(dir, file);
const stat = FS.statSync(fdir);
if (!stat) {
return;
}
if (stat.isDirectory()) {
if (file !== 'node_modules' && !file.startsWith('.')) {
rs = rs.concat(findJs(fdir));
}
} else if (stat.isFile()) {
if (file.endsWith('.js') || file.endsWith('.ts')) {
rs.push(fdir);
}
}
});
return rs;
}
function paserUrl(url) {
if (url.startsWith('/')) {
return cwd + url;
} else if (url.startsWith('./') || url.startsWith('../')) {
return __dirname + url;
}
return url;
}
}
/**
* 拦截器实例化
* @param cfg {undefined|string|string[]}
* @param conn {Object}
* @param setting {Object}
* @return {undefined|Interceptors[]}
*/
static #intercepts(cfg, { conn, setting }) {
if (!cfg) {
return;
}
let list = Array.isArray(cfg) ? cfg : [ cfg ];
return list.filter(Boolean)
.map(im => {
if (typeof im != 'string') { // 已实例化,或直接给了拦截器对象
return im;
}
let Interceptor = Interceptors[ im ];
if (Interceptor) {
if (isObj(Interceptor)) {
return Interceptor;
} else if (typeof Interceptor == 'function') {
return new Interceptor({ maxTimeout: conn.requestTimeout, level: setting.intercept?.logLevel });
}
throw new Error(`RMQ messageInterceptor: ${im} 定义错误,仅支持[function, Object]`);
}
let itrs = Object.entries(Interceptors)
.filter(([ , f ]) => typeof f == 'function' || isObj(f))
.map(([ k ]) => k);
throw new Error(`RMQ messageInterceptor: ${im} 未定义,可选:${JSON.stringify(itrs)}`);
});
}
/**
* @return {RMQ}
*/
static of() {
return new RMQ(...arguments);
}
}
/**
* 集群配置
*/
const cluster = Object.entries(cfgs)
.reduce((pre, [ k, cfg ]) => {
pre[ k ] = RMQ.of(cfg);
return pre;
}, Object.create(null));
/**
* 关闭集群所有连接
*/
async function close() {
const rs = Object.entries(cluster).map(async ([ name, { producer, consumer, ...clients } ]) => {
clients = [ consumer, ...Object.values(clients) ].filter(Boolean);
if (!clients.length) {
return true;
}
let clos = clients.flatMap(Object.values);
clos = Array.from(new Set(clos).add(producer))
.map(client => (client.close || client.shutdown || client.exit)?.());
const r = await Promise.allSettled(clos);
const ok = r.every(x => x.status === 'fulfilled');
!ok && log.error('RMQ: [%s]集群关闭异常', name);
return ok;
})
let prms = await Promise.allSettled(rs);
return prms.every(x => x.status === 'fulfilled' && x.value);
}
/**
* RocketMQ
*/
module.exports = {
...cluster, // 直接将集群名称导出给调用方。这只是使用方式之一,推荐直接引入 setting.scan 下的文件。
close,
};
Interceptor.js - 消息日志拦截器
js
const { Attribute, AttributeKey, MessageHookPoints, MessageHookPointsStatus, CONSUME_ERROR_CONTEXT_KEY, CONSUMER_GROUP_CONTEXT_KEY } = require('rocketmq-client-nodejs');
const { log, log4js: { levels } } = require('../log');
/**
* 消息钩子枚举
*/
class MsgHook {
constructor({ k, v }) {
this.k = k;
this.v = v;
}
eq(k) {
return this === k || this.k === k;
}
/**
* 获取枚举
*/
static get(k) {
if (k == null) {
return;
}
const ks = Object.getOwnPropertyNames(MsgHook);
const ens = ks.filter(k => MsgHook[ k ] instanceof MsgHook);
return ens.find(im => im.k === k);
}
static #UNKNOWN = new MsgHook({ k: 'UNKNOWN', v: '未知消息事件' });
/**
* 未知消息事件
*/
static get UNKNOWN() {
return MsgHook.#UNKNOWN;
}
static #SEND = new MsgHook({ k: MessageHookPoints.SEND, v: '发送消息' });
/**
* 发送消息
*/
static get SEND() {
return MsgHook.#SEND;
}
static #RECEIVE = new MsgHook({ k: MessageHookPoints.RECEIVE, v: '拉取消息' });
/**
* 拉取消息
*/
static get RECEIVE() {
return MsgHook.#RECEIVE;
}
static #CONSUME = new MsgHook({ k: MessageHookPoints.CONSUME, v: '收到消息' });
/**
* 收到消息
*/
static get CONSUME() {
return MsgHook.#CONSUME;
}
static #ACK = new MsgHook({ k: MessageHookPoints.ACK, v: '确认消息' });
/**
* 确认消息
*/
static get ACK() {
return MsgHook.#ACK;
}
static #CHANGE_INVISIBLE_DURATION = new MsgHook({ k: MessageHookPoints.CHANGE_INVISIBLE_DURATION, v: '延长不可见时长' });
/**
* 延长不可见时长
*/
static get CHANGE_INVISIBLE_DURATION() {
return MsgHook.#CHANGE_INVISIBLE_DURATION;
}
static #COMMIT_TRANSACTION = new MsgHook({ k: MessageHookPoints.COMMIT_TRANSACTION, v: '提交事务' });
/**
* 提交事务
*/
static get COMMIT_TRANSACTION() {
return MsgHook.#COMMIT_TRANSACTION;
}
static #ROLLBACK_TRANSACTION = new MsgHook({ k: MessageHookPoints.ROLLBACK_TRANSACTION, v: '回滚事务' });
/**
* 回滚事务
*/
static get ROLLBACK_TRANSACTION() {
return MsgHook.#ROLLBACK_TRANSACTION;
}
static #FORWARD_TO_DLQ = new MsgHook({ k: MessageHookPoints.FORWARD_TO_DLQ, v: '转死信' });
/**
* 转死信
*/
static get FORWARD_TO_DLQ() {
return MsgHook.#FORWARD_TO_DLQ;
}
}
/**
* 公共消息日志
*/
class MsgLog {
/**
* 最大耗时阈值
* @type {number}
*/
#maxTimeout;
/**
* 耗时统计Key
* @type {AttributeKey<number>}
*/
#timeoutKey;
/**
* 日志级别
*/
level = levels.DEBUG;
/**
* @param maxTimeout {number} 最大耗时阈值
* @param timeoutKey {string} 耗时统计Key
* @param level {levels} 日志级别
*/
constructor({ maxTimeout, level, timeoutKey = 'timeout' } = {}) {
this.#maxTimeout = maxTimeout && maxTimeout > 0 ? +maxTimeout : MsgLog.TIMEOUT;
this.#timeoutKey = AttributeKey.create(timeoutKey);
if (level) {
level = typeof level == 'string' ? levels[ level.toUpperCase() ] : level;
this.level = level || levels.DEBUG;
}
}
/**
* 耗时阈值
* @return {number}
*/
static get TIMEOUT() {
return 10000;
}
/**
* 消息分发前
*/
doBefore(ctx, msgs = []) {
ctx.putAttribute(this.#timeoutKey, Attribute.create(Date.now()));
return null;
}
/**
* 消息分发后
*/
doAfter(ctx, msgs = []) {
let r = MsgLog.doRes(ctx, msgs);
let err = ctx.getStatus() === MessageHookPointsStatus.ERROR;
let start = ctx.getAttribute(this.#timeoutKey)?.get();
if (start != null) {
let cost = r.cost = Date.now() - start;
if (cost > this.#maxTimeout) {
!err && !MsgHook.RECEIVE.eq(r.MsgHook) && log.warn('RMQ: 耗时严重 %s ms,%s(%s) %s', cost, r.MsgHook.getV(), r.MsgHook.getK(), r.msg);
}
}
if (err) {
let args = [ r.cost, r.MsgHook.getV(), r.MsgHook.getK(), r.msg ];
if (MsgHook.CONSUME.eq(r.MsgHook)) {
args.push(ctx.getAttribute(CONSUME_ERROR_CONTEXT_KEY)?.get());
}
let level = MsgHook.RECEIVE.eq(r.MsgHook) ? levels.INFO : levels.ERROR;
log.isLevelEnabled(level) && log.log(level, 'RMQ: After发生错误,耗时 %s ms,%s(%s) %s', ...args);
}
return r;
}
/**
* 是否启用指定级别日志
* @return {boolean}
*/
isEnabled() {
return log.isLevelEnabled(this.level);
}
/**
* 精简消息:去掉不宜进日志的内容
* @param msgs {GeneralMessage[]}
* @return {object[]}
*/
static brief(msgs) {
return (msgs ?? []).map(im => {
if (im == null || typeof im != 'object') {
return im;
}
let pre = {};
let omit = MsgLog.OMIT;
for (const k in im) {
if (k.startsWith('#') || k.startsWith('_') || omit.includes(k)) {
continue;
}
let v = im[ k ];
if (v == null || typeof v == 'function') {
continue;
}
if (v instanceof Map) {
v = v.size <= 99 ?
JSON.stringify(v) :
'Map(' + v.size + ')';
} else if (Buffer.isBuffer(v)) {
let max = 256;
v = v.length <= max ?
v.toString('utf8') :
'(' + v.length + ')' + v.toString('utf8', 0, max);
}
pre[ k ] = v;
}
return pre;
});
}
static doRes(ctx, msgs) {
return new Proxy({}, {
get: (target, p) => {
let own = target[ p ];
if (own != null) {
return own;
}
if (p === 'msg') {
own = target[ p ] = JSON.stringify(MsgLog.brief(msgs));
} else if (p === 'MsgHook') {
own = target[ p ] = MsgHook.get(ctx.getMessageHookPoints()) || MsgHook.UNKNOWN;
} else if (p === 'group') {
own = target[ p ] = RecvLog.group(ctx);
}
return own;
}
});
}
/**
* 日志中省略的字段
*/
static get OMIT() {
return [ 'endpoints' ];
}
/**
* @return {MsgLog}
*/
static of() {
return new MsgLog(...arguments);
}
}
/**
* 发送消息日志
*/
class SendLog extends MsgLog {
constructor(args) {
super(args);
}
/**
* 消息分发前
* @param ctx {MessageInterceptorContext}
* @param msgs {GeneralMessage[]}
*/
doBefore(ctx, msgs = []) {
try {
var r = super.doBefore(ctx, msgs);
this.#before(ctx, msgs, r);
} catch (e) {
!r && (r = MsgLog.doRes(ctx, msgs) || {});
log.error('RMQ: 待发消息,日志打印异常%s(%s) %s', r.MsgHook?.getV(), r.MsgHook?.getK(), r.msg, e);
}
}
/**
* 消息分发后
* @param ctx {MessageInterceptorContext}
* @param msgs {GeneralMessage[]}
*/
doAfter(ctx, msgs = []) {
try {
var r = super.doAfter(ctx, msgs);
this.#after(ctx, msgs, r);
} catch (e) {
r ??= {};
log.error('RMQ: 消息已发送,日志打印异常,耗时 %s ms,%s(%s) %s', r.cost, r.MsgHook?.getV(), r.MsgHook?.getK(), r.msg, e);
}
}
#before(ctx, msgs, r) {
if (!this.isEnabled()) {
return;
}
!r && (r = MsgLog.doRes(ctx, msgs));
log.log(this.level, 'RMQ: 待发消息 %s(%s) %s', r.MsgHook.getV(), r.MsgHook.getK(), r.msg);
}
#after(ctx, msgs, r) {
if (!this.isEnabled()) {
return;
}
log.log(this.level, 'RMQ: 消息已发送,耗时 %s ms,%s(%s) %s', r.cost, r.MsgHook.getV(), r.MsgHook.getK(), r.msg);
}
/**
* @return {SendLog}
*/
static of() {
return new SendLog(...arguments);
}
}
/**
* 接收消息日志
*/
class RecvLog extends MsgLog {
constructor(args) {
super(args);
}
/**
* 消息分发前
* @param ctx {MessageInterceptorContext}
* @param msgs {GeneralMessage[]}
*/
doBefore(ctx, msgs = []) {
try {
var r = super.doBefore(ctx, msgs);
this.#before(ctx, msgs, r);
} catch (e) {
!r && (r = MsgLog.doRes(ctx, msgs) || {});
log.error('RMQ: 待收消息[%s],日志打印异常 %s(%s) %s', r.group, r.MsgHook?.getV(), r.MsgHook?.getK(), r.msg, e);
}
}
/**
* 消息分发后
* @param ctx {MessageInterceptorContext}
* @param msgs {GeneralMessage[]}
*/
doAfter(ctx, msgs = []) {
try {
var r = super.doAfter(ctx, msgs);
this.#after(ctx, msgs, r);
} catch (e) {
r ??= {};
log.error('RMQ: 收到消息[%s],日志打印异常,耗时 %s ms,%s(%s) %s', r.group, r.cost, r.MsgHook?.getV(), r.MsgHook?.getK(), r.msg, e);
}
}
#before(ctx, msgs, r) {
if (!this.isEnabled()) {
return;
}
!r && (r = MsgLog.doRes(ctx, msgs));
if (!MsgHook.CONSUME.eq(r.MsgHook)) {
return;
}
log.log(this.level, 'RMQ: 待收消息[%s] %s(%s) %s', r.group, r.MsgHook.getV(), r.MsgHook.getK(), r.msg);
}
#after(ctx, msgs, r) {
if (!this.isEnabled()
|| [ MsgHook.ACK, MsgHook.CHANGE_INVISIBLE_DURATION, MsgHook.FORWARD_TO_DLQ ].includes(r.MsgHook)
) {
return;
}
if (MsgHook.RECEIVE.eq(r.MsgHook) && !msgs.length) {
log.debug('RMQ: %s(%s),耗时 %s ms,[%s]无消息', r.MsgHook.getV(), r.MsgHook.getK(), r.cost, r.group || '');
return;
}
log.log(this.level, 'RMQ: 收到消息[%s],耗时 %s ms,%s(%s) %s', r.group, r.cost, r.MsgHook.getV(), r.MsgHook.getK(), r.msg);
}
/**
* 消费组前缀(消费侧独有)
* @param ctx {MessageInterceptorContext}
* @return {string}
*/
static group(ctx) {
return ctx.getAttribute(CONSUMER_GROUP_CONTEXT_KEY)?.get();
}
/**
* @return {RecvLog}
*/
static of() {
return new RecvLog(...arguments);
}
}
/**
* 拦截器
*/
module.exports = {
MsgLog,
SendLog,
RecvLog,
};
index.js
js
const Client = require('./Client');
/**
* RocketMQ
*/
module.exports = {
...Client,
};
const rmq = require('./RocketMQ'); // 放在上面会出现依赖循环崩溃
Object.assign(module.exports, rmq);
Producer / Consumer 目录结构
项目目录示例:
/src/main/js/com/x/x/{common, controller, service, mq}/。配置文件指定扫描到此目录/src/main/js/com/x/x/mq/{集群名称async, sync}/{producer, consumer}/
Producer 文件目录
Topic命名规约:前缀tp_系统名_业务/服务名_消息类型normal,delay,fifo,transaction。
例如:
tp_biz_user_normal表示 业务系统_用户服务_普通消息。tp_1d_delay表示 延时1天消息类型。tp_biz_pay_fifo表示 业务系统_支付_顺序消息。
- 普通消息Topic tp_biz_server_name_normal :
/src/main/js/com/x/x/mq/async/producer/BizServerNameNormal.js - 3分钟延时Topic tp_3m_delay :
/src/main/js/com/x/x/mq/async/producer/3mDelay.js
Consumer 文件目录
Group命名规约:前缀g_系统名_业务/服务名。
例如:
g_biz_user表示业务系统_用户服务 消费组。g_biz_pay表示业务系统_支付 消费组。
- 普通消息Topic tp_biz_server_name_normal 消费组:
/src/main/js/com/x/x/mq/async/consumer/biz/user/BizServerNameNormal.js - 3分钟延时Topic tp_3m_delay 消费组:
/src/main/js/com/x/x/mq/async/consumer/biz/pay/3mDelay.js
使用示例
js
/** 发送普通消息 */
const { bizServerNameNormal } = require('/src/main/js/com/x/x/mq/async/producer/BizServerNameNormal');
/** 发送延时消息 */
const { 3mDelay } = require('/src/main/js/com/x/x/mq/async/consumer/biz/user/3mDelay');
await bizServerNameNormal.updateUser({ id: 1, name: 'userName' });
await 3mDelay.depay({ payId: '2000_xx' });
- 发送消息
/src/main/js/com/x/x/mq/async/producer/BizServerNameNormal.js代码示例
js
const { AutoTopic } = require('@/common/cfg/mq/Client');
/**
* 普通消息
*/
class BizServerNameNormal extends AutoTopic {
constructor(args) {
return super(args);
}
/** 更新用户信息 */
updateUser(msg) {
console.log('发送消息内容:', msg);
return msg;
}
}
/**
* 普通消息
*/
module.exports = {
BizServerNameNormal,
/* bizServerNameNormal: new BizServerNameNormal(), 框架会自动添加一个首字母小写的单实例 */
};
- 接收消息
/src/main/js/com/x/x/mq/async/consumer/biz/user/BizServerNameNormal.js代码示例
js
const { Group } = require('@/common/cfg/mq/Client');
/**
* 接收/消费 - 普通消息
*/
class BizServerNameNormal extends Group {
constructor(args) {
super(args);
}
/** 更新用户信息 */
updateUser({ body, topic, tag, messageId } = {}) {
console.log('收到消息:', topic, tag, messageId, body);
if (!body.id) {
throw new Error('用户信息有误'); // 抛异常 或 返回Promise.reject(),都会根据RMQ的退避策略自动重试
}
/* 正常返回任意值,都会自动ACK成功 */
return body.id % 2 === 0 ? undefined : Promise.reject(new Error('测试自动重试'));
}
}
/**
* 接收/消费 - 普通消息
*/
module.exports = {
BizServerNameNormal,
/* bizServerNameNormal: new BizServerNameNormal(), 框架会自动添加一个首字母小写的单实例 */
};
使用过程中,若出现bug,或有其它优化建议,欢迎在此文章"评论区"留言讨论,并留下您的邮箱,以便改正后及时通知您。