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