【问题标题】:Node: Unable to call continuation-local-storage key inside gRPC callback using express节点:无法使用 express 在 gRPC 回调中调用 continuation-local-storage 键
【发布时间】:2018-11-29 07:32:02
【问题描述】:

我正在尝试将 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 请求中获取命名空间中的值?

【问题讨论】:

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


    【解决方案1】:

    我决定改用 cls-hooked。 continuation-local-storage 的分支似乎效果更好。只需确保您的节点版本 >= 9。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      相关资源
      最近更新 更多