NodeJS TransactionID 与 Continuation-local-storage

2024-03-14

各位,我想在 NodeJS 中实现事务 ID 跟踪。读完这篇文章后,https://datahero.com/blog/2014/05/22/node-js-preserving-data-across-async-callbacks/ https://datahero.com/blog/2014/05/22/node-js-preserving-data-across-async-callbacks/,我从代码中得到以下错误:

var server = express();
var getNamespace = require('continuation-local-storage').getNamespace
var namespace = getNamespace('com.me')
var uuid = require('node-uuid');

// create a transaction id for each request
server.use(function(req, res, next) {
    var tid = uuid.v4();

    // wrap the events from request and response
    namespace.bindEmitter(req);
    namespace.bindEmitter(res);

    // run following middleware in the scope of
    // the namespace we created
    namespace.run(function() {

        // set tid on the namespace, makes it
        // available for all continuations
        namespace.set('tid', tid);
        next();
    });
});

error:

TypeError: Cannot call method 'bindEmitter' of undefined

各位, 这是有效的正确代码:

var express = require('express');
var server = express();

var cls = require('continuation-local-storage');
var namespace = cls.createNamespace('com.me');

var uuid = require('node-uuid');

// create a transaction id for each request
server.use(function(req, res, next) {
    var namespace = cls.getNamespace('com.me');
    var tid = uuid.v4();

    // wrap the events from request and response
    namespace.bindEmitter(req);
    namespace.bindEmitter(res);

    // run following middleware in the scope of
    // the namespace we created
    namespace.run(function() {

        // set tid on the namespace, makes it
        // available for all continuations
        namespace.set('tid', tid);
        next();
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NodeJS TransactionID 与 Continuation-local-storage 的相关文章

随机推荐