当前位置:网站首页>The nodejs service global timeout callback failed to get process Domain problem

The nodejs service global timeout callback failed to get process Domain problem

2022-06-24 10:43:00 Mongolia Shangdan 2

There is a problem with our server , When triggered express After global timeout for , stay server.setTimeout In the callback of ,process.domain yes undefined.

As we will generate each visit reqId、 user id Wait for the information to be saved in process.domain in . If you can't get it process.domain, It is difficult for us to find out the error log in the massive logs , It makes it difficult to troubleshoot online problems .

Here is the simplified code :

const domain = require('domain');
const express = require('express');
const app = express();
const http = require('http');
const sleep = (ts) => (new Promise(resolve => setTimeout(resolve, ts)))

app.use((req, res, next) => {
    const d = domain.create();
    d.id = 999999;
    d.add(req);
	d.add(res);
	d.run(next);
});

let testRouter = express.Router();
testRouter.get('/', async function (req, res) {
    await sleep(2000);// etc. 2 second , Let the program enter the global timeout logic 
    res.send('hello world!');
});
app.use('/test', testRouter);

const server = http.createServer(app).listen(3000, '127.0.0.1', () => {});

server.setTimeout(1000, (socket) => {
    console.log(process.domain);// The result here is undefined
});

stay stackoverflow in , I saw an old man saying it was domain Scope problem , You must mount the correct scope to domain in . I tried , Found a solution .

So what we wrote was :

d.add(req);
d.add(res);

The solution is to req.socket Also added domain Go to the scope , That is, the following writing :

d.add(req);
d.add(res);
d.add(req.socket);

I don't understand this yet domain What is the scope , We will continue to study it later domain Source code of the component :

https://github.com/nodejs/node/blob/master/lib/domain.js

原网站

版权声明
本文为[Mongolia Shangdan 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210619230150918w.html