我有一个clsBinder.js文件,其中包含以下代码:
const cls = require('cls-hooked');
const messages = require('./customMessages');
const config = require('./config');
module.exports = (ns) => {
// if no namespace were provided, throw an error
if (!ns) throw new Error(messages.errors.requiredNamespace);
// generate, set and bind a correlationId on the given namespace
return function clsifyMiddleware(req, res, next) {
ns.bindEmitter(req);
ns.bindEmitter(res);
// and initialize the namespace
ns.run(() => {
cls.getNamespace(config.cls.correlationIdNamespace)
.set(config.cls.correlationIdName, { header: 'ApiGateway-Correlation-ID' });
next();
});
};
};
在set()中,我通过提供我们在api网关中使用的名称,为correlation-id添加了标头。
在另一个文件中,我有以下代码用于发布队列:
const publishToDirectPersistentQueue = (queue, message, connection = CONNECTIONS.INTERNAL) => {
const channel = createDurableChannel(queue, connection);
return channel.sendToQueue(queue, message, { contentType: 'application/json', persistent: true }, { headers: 'ApiGateway-Correlation-ID' })
.then(() => {
logger.debug(`Published on ${queue} the message: ${JSON.stringify(Object.assign({}, message, { password: undefined, password_investor: undefined }))}`);
channel.close();
return true;
}).catch((err) => {
logger.debug(`Publish on ${queue} failed: ${err.toString()}`);
channel.close();
// TODO: do we need to retry or it will happen automatically?
return err;
});
};
这里我也添加了标头...但是我想知道这是否是从cls获取correlation_id并将其设置在标头上的正确方法? 我需要做的第二件事是从消费者的队列中获取标头并将其设置在cls上。。。有人可以帮我这个忙吗?