在Node中访问长时间运行进程的grpc流变量

时间:2022-03-22 22:41:42

I am using Node.js to connect to a server using gRPC that performs a long running task.

我正在使用Node.js使用执行长时间运行任务的gRPC连接到服务器。

The server sends a unidirectional stream to the client (the Node.js app) while the job is in progress. I need to implement a Stop button and am told that closing the gRPC stream will stop the job in progress.

在作业正在进行时,服务器将单向流发送到客户端(Node.js应用程序)。我需要实现一个停止按钮,并告知关闭gRPC流将停止正在进行的作业。

This is currently my code:

这是我目前的代码:

let express = require('express'),
    router = express.Router(),
    grpc = require('grpc'),
    srv = grpc.load(__dirname + '/job_handler.proto').ns;

let startJob = (jobID, parameters) => srv.createJob(jobID, parameters);

router.post('/jobs', (req, res) => {
    let lengthyOperation = startJob(jobID, parameters);
    lengthyOperation.on('data', (data) => {
        console.log(`Data from lengthy operation: ${data}`);
    });

    lengthyOperation.on('end', () =>
        console.log('Lengthy operation completed');
    });

    res.setHeader('Location', `/jobs/${jobID}`);
    res.status(202).send();
});

As you can see, I send an HTTP 202 response to the client upon creating the job and it continues asynchronously in the background.

如您所见,我在创建作业时向客户端发送HTTP 202响应,并在后台异步继续。

Questions:

  1. How do I close the stream?
  2. 如何关闭流?

  3. How do I access the lengthyOperation variable to do so?
  4. 如何访问lengthyOperation变量来执行此操作?

1 个解决方案

#1


2  

The lengthyOperation object has a cancel method that cancels the call. So, when you want to stop the stream, just call lengthyOperation.cancel().

lengthyOperation对象有一个取消方法取消该调用。因此,当您想要停止流时,只需调用lengthyOperation.cancel()。

Note that when you do this, it will cause the call to end with an error. I would recommend adding a lengthyOperation.on('error', ...) handler to handle that error.

请注意,执行此操作时,将导致调用以错误结束。我建议添加一个lengthyOperation.on('error',...)处理程序来处理该错误。

#1


2  

The lengthyOperation object has a cancel method that cancels the call. So, when you want to stop the stream, just call lengthyOperation.cancel().

lengthyOperation对象有一个取消方法取消该调用。因此,当您想要停止流时,只需调用lengthyOperation.cancel()。

Note that when you do this, it will cause the call to end with an error. I would recommend adding a lengthyOperation.on('error', ...) handler to handle that error.

请注意,执行此操作时,将导致调用以错误结束。我建议添加一个lengthyOperation.on('error',...)处理程序来处理该错误。