从现在开始负秒数后,Grpc 抛出截止时间超出

Grpc throws deadline exceeded after negative number of seconds from now

第一次调用通常会成功,但随后出现异常消息:

io.grpc.StatusRuntimeException:DEADLINE_EXCEEDED:ClientCall 在超过截止日期后开始:-175.597476157s 从现在开始

为什么秒数是负数?我该如何解决?

我的 grpc 配置:

public class MyAppLibGrpcSenderConfig {

    @Value("${grpc.client.host:localhost}")
    private String host;
    @Value("${grpc.client.port:9090}")
    private int port;
    @Value("${grpc.client.negotiationType:PLAINTEXT}")
    private String negotiationType;
    @Value("${grpc.client.deadline:300000}")
    private long deadline;

    @Autowired
    private Tracer tracer;

    @Bean
    public ManagedChannel managedChannel() {
        ManagedChannelBuilder<?> builder = ManagedChannelBuilder.forAddress(host, port);
        if ("PLAINTEXT".equals(negotiationType)) {
            builder.usePlaintext();
        }
        return builder.build();
    }

    @Bean
    public TracingClientInterceptor tracingClientInterceptor(Tracer tracer) {
        return TracingClientInterceptor
                .newBuilder()
                .withTracer(this.tracer)
                .build();
    }

    @Bean
    public MyAppSenderServiceGrpc.MyAppSenderServiceBlockingStub myAppSenderServiceBlockingStub(
            TracingClientInterceptor tracingClientInterceptor,
            ManagedChannel managedChannel) {
        return MyAppSenderServiceGrpc
                .newBlockingStub(tracingClientInterceptor.intercept(managedChannel))
                .withDeadlineAfter(deadline, TimeUnit.MILLISECONDS);
    }

    @Bean
    public MyAppCodeLoaderServiceGrpc.MyAppCodeLoaderServiceBlockingStub myAppCodeLoaderServiceBlockingStub(
            TracingClientInterceptor tracingClientInterceptor,
            ManagedChannel managedChannel) {
        return MyAppCodeLoaderServiceGrpc
                .newBlockingStub(tracingClientInterceptor.intercept(managedChannel))
                .withDeadlineAfter(deadline, TimeUnit.MILLISECONDS);
    }
}

客户代码:

@net.devh.boot.grpc.server.service.GrpcService
public class MyAppEventKafkaSender extends MyAppSenderServiceGrpc.MyAppSenderServiceImplBase {

    ...
    
    @SneakyThrows
    @Override
    public void sendMessage(ContextMyAppEventGrpc contextMyAppEventGrpc,
                            StreamObserver<Empty> responseObserver) {
        try {
            sendEvent(contextMyAppEventGrpc);
            Empty reply = Empty.newBuilder().build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            Status status = Status.INTERNAL.withDescription(e.getMessage());
            responseObserver.onError(status.asRuntimeException());
        }
    }
    
}

Deadline 是一个绝对时间点,在您创建存根时立即设置(不一定在您执行它时)——这与相对超时形成对比到通话开始。

所以负期限意味着它在您的存根被执行之前就已经过期了。

要解决此问题,您应该在拨打电话前立即设置截止日期

var response = blockingStub.withDeadlineAfter(300000, TimeUnit.MILLISECONDS)
                           .yourRpcName();

阅读有关截止日期的更多信息here