简体   繁体   English

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

[英]Access grpc stream variable for long-running process in Node

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. 在作业进行期间,服务器将单向流发送到客户端(Node.js应用程序)。 I need to implement a Stop button and am told that closing the gRPC stream will stop the job in progress. 我需要实现一个“停止”按钮,并被告知关闭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. How do I access the lengthyOperation variable to do so? 我该如何访问lengthyOperation变量呢?

The lengthyOperation object has a cancel method that cancels the call. lengthyOperation对象具有cancel调用的cancel方法。 So, when you want to stop the stream, just call lengthyOperation.cancel() . 因此,当您要停止流时,只需调用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', ...)处理程序来处理该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM