node.js - Node : Unable to call continuation-local-storage key inside gRPC callback using express

标签 node.js grpc-node continuation-local-storag

我正在尝试将 ID 存储在 continuation-local-storage 中,以便我可以在成功的 gRPC 请求后将其输出到日志中。我在应用程序启动时创建命名空间,然后在中间件中设置 ID(在完整实现中,ID 将出现在请求中)。然后我尝试在 get('/') 中获取 ID。获取 ID 有效,但我无法在 gRPC 请求中获取它:

app.js

const cls = require('continuation-local-storage');
cls.createNamespace("THING");
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var app = express();

const storeRequestId = (req, res, next) => {
  const ns = cls.getNamespace("THING");
  ns.run(() => {
    ns.set('thing-id', '123');
    next();
  });
}
app.use(storeRequestId);

app.use('/', index);

module.exports = app;

index.js

const cls = require('continuation-local-storage');
var express = require('express');
var router = express.Router();
var grpc = require('grpc');
const path = 'path/to/proto'
const rootPath = 'root/path'
console.log({root: rootPath, file: path})

const identityService = grpc.load({root: rootPath, file: path}).identity.service;
const grpcCredentials = grpc.credentials.createInsecure();
const identityClient = new identityService.Identity('localhost:8020', grpcCredentials)

/* GET home page. */
router.get('/', function(req, res, next) {
  ns = cls.getNamespace('THING');
  console.log(ns.get('thing-id'));

  const retrievePartyReq = {
    party_id: 'party123',
  }

  identityClient.retrieveParty(retrievePartyReq, (err, response) => {
    ns = cls.getNamespace('THING');
    console.log(ns.get('thing-id'));
  })

  res.status(200).send('200: All is good.');
});

module.exports = router;

这在日志中输出:

123
undefined

我预计两次都是 123。为什么我无法从 gRPC 请求中的命名空间获取值?

最佳答案

我决定改用 cls-hooked。延续本地存储的分支似乎工作得更好。只需确保您的 Node 版本 >= 9。

关于node.js - Node : Unable to call continuation-local-storage key inside gRPC callback using express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53533900/

相关文章:

node.js - grpc 尝试连​​接 http1.x 服务器

node.js - 连续本地存储上下文在异步 waterfall 中丢失

javascript - Node : res. 发送数组不起作用

javascript - AJAX 调用并在 Node 中获取返回数据

javascript - Mongoose 从远程服务器获取外部数据

node.js - cassandra-driver (Node.js) 中同步查询执行的问题

javascript - npm install 上的 node-pre-gyp 安装错误