具有Continuation-local-storage的NodeJS TransactionID

时间:2014-09-17 01:17:48

标签: node.js

伙计们,我想在NodeJS中实现事务ID跟踪。阅读本文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();
    });
});

错误:

TypeError: Cannot call method 'bindEmitter' of undefined

3 个答案:

答案 0 :(得分:5)

民间,   以下是正确的代码:

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();
    });
});

答案 1 :(得分:0)

对于任何因为使用异步功能使用continuation-local-storage遇到问题而来到这里的人,也请尝试与Node的新async_hooks API集成的库的此派生。

cls-hooked

答案 2 :(得分:0)

首先,我们需要创建名称空间,然后尝试访问该名称空间。

var ns = cls.createNamespace('com.me'); 

然后在任何可能是中间件的方法中,像访问它一样

ns = cls.getNamespace('com.me'); 

如果您处于创建命名空间的相同环境中,则可以使用变量“ ns”本身。

尽管这是一个过时的帖子,但希望对某人有所帮助;)

美好的一天!