在 node js 中为 grpc 函数设置超时

Sta*_*ley 6 node.js grpc

尝试在服务器 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
    })
Run Code Online (Sandbox Code Playgroud)

piy*_*thi 7

您还可以将 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 )

}
Run Code Online (Sandbox Code Playgroud)

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

var deadline = getRPCDeadline(1)

grpcClient.hello({message: "abc"},{deadline: deadline}, function(err, response) {
    console.log(err)
    console.log(response)
});
Run Code Online (Sandbox Code Playgroud)

  • 这是正确答案。请使用呼叫选项指定截止日期。“接受的答案”是杂乱无章的,不应使用。 (2认同)

Sta*_*ley 5

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

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)
});
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考:gRPC 不使用“超时”(这是相对的,例如 5 秒),而是使用“截止日期”(绝对时间点)。这可能就是您找不到它的原因。 (3认同)