Node.js 节点:无法使用express调用gRPC回调内的延续本地存储密钥
我正试图在本地存储中存储一个ID,以便在gRPC请求成功后将其输出到日志中。我在应用程序开始时创建名称空间,然后在中间件中设置ID(在完整的实现中,ID将出现在请求中)。然后,我尝试在get(“/”)中获取ID。获取ID有效,但我无法在gRPC请求中获取ID: app.jsNode.js 节点:无法使用express调用gRPC回调内的延续本地存储密钥,node.js,grpc-node,continuation-local-storag,Node.js,Grpc Node,Continuation Local Storag,我正试图在本地存储中存储一个ID,以便在gRPC请求成功后将其输出到日志中。我在应用程序开始时创建名称空间,然后在中间件中设置ID(在完整的实现中,ID将出现在请求中)。然后,我尝试在get(“/”)中获取ID。获取ID有效,但我无法在gRPC请求中获取ID: app.js const cls = require('continuation-local-storage'); cls.createNamespace("THING"); var express = require('express'
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。本地存储的分支似乎工作得更好。只需确保您的节点版本>=9