我有一个节点http server.It有一个主进程,我有分叉的子进程/ webworker。
我希望主节点进程处理http请求并将此请求传递给分叉进程或Web worker,以便它们可以独立处理请求并向其发送响应。
问题: - 我无法将响应对象发送给子进程/ web-worker。
节点也不允许共享变量。所以我不能将它存储在父进程上并与子进程共享它的引用。
有什么方法可以吗?
答案 0 :(得分:0)
正如您所说,您无法传递响应对象。但是,您可以传递某种标识符,使主线程在工作人员完成其工作时检索正确的响应对象。
例如你可以
以下是基本实现
var http = require('http');
var Worker = require('webworker-threads').Worker;
// Store in-progress responses by unique(-enough) ID
// that is passed to the worker that then passes it back
var responses = {
_nextResponseId: 0,
_responses: {},
store: function store(response) {
var id = this._nextResponseId;
this._nextResponseId = this._nextResponseId === Number.MAX_SAFE_INTEGER ? 0 : (this._nextResponseId + 1);
this._responses[id] = response;
return id;
},
remove: function remove(id) {
var response = this._responses[id];
delete this._responses[id];
return response;
}
};
// Worker,simulating something long and synchronous
var worker = new Worker(function() {
onmessage = function(event) {
var id = event.data.id;
for (var i = 0; i < 1000000000; ++i) {}
self.postMessage({
id: id,
message: 'From worker, request ' + id
});
};
});
// A worker message ends the original http response
worker.onmessage = function(event) {
var response = responses.remove(event.data.id);
response.end(event.data.message);
};
// Simple server that calls the worker with the id of the response
var server = http.createServer(function handleRequest(request, response) {
var id = responses.store(response);
worker.postMessage({
id: id
});
});
server.listen(8083);