在节点js中为grpc函数设置超时

Setting timeouts for grpc functions in node js

尝试在服务器 grpc 实现未指定回调函数的情况下为 grpc 连接创建超时,但似乎无论选项中指定什么 (new Date().getSeconds() +5) 客户端没有终止连接

    function hello (call, callback) {
        console.log(call.request.message)
    }
    server.addService(client.Hello.service, {hello: hello});
    server.bind('localhost:50051', grpc.ServerCredentials.createInsecure());
    server.start();
    grpcClient = new client.Hello('localhost:50051',
        grpc.credentials.createInsecure(),{deadline: new Date().getSeconds()+5}); //


    grpcClient.hello({message: "abc"}, function(err, response) {
        console.log(response) // doesn't reach here because function hello doesn't callback
    })

好的,似乎可以使用以下代码:

var timeout_in_seconds = 5
var timeout = new Date().setSeconds(new Date().getSeconds() + timeout_in_seconds)

grpcClient.hello({message: "abc"},{deadline: timeout}, function(err, response) {
    console.log(err)
    console.log(response)
});

https://grpc.io/docs/guides/concepts.html#cancelling-rpcs

Deadlines/Timeouts

gRPC allows clients to specify how long they are willing to wait for an RPC to complete before the RPC is terminated with the error DEADLINE_EXCEEDED. On the server side, the server can query to see if a particular RPC has timed out, or how much time is left to complete the RPC.

How the deadline or timeout is specified varies from language to language - for example, not all languages have a default deadline, some language APIs work in terms of a deadline (a fixed point in time), and some language APIs work in terms of timeouts (durations of time).

您也可以将 rpc 截止时间设置为:

function getRPCDeadline(rpcType) {

    timeAllowed = 5000
    switch(rpcType) {

        case 1:
            timeAllowed = 5000  // LIGHT RPC
            break

        case 2 :
            timeAllowed = 7000  // HEAVY RPC
            break

        default :
            console.log("Invalid RPC Type: Using Default Timeout")

    }

    return new Date( Date.now() + timeAllowed )

}

然后在调用任何 rpc 时使用此函数:

var deadline = getRPCDeadline(1)

grpcClient.hello({message: "abc"},{deadline: deadline}, function(err, response) {
    console.log(err)
    console.log(response)
});