GRPC服务端推流异常

现象

  • 日志发生以下异常
    - INTERNAL: Connection closed after GOAWAY. HTTP/2 error code: INTERNAL_ERROR, debug data: Stream 5 sent too many headers EOS: false
    - INTERNAL: Invalid protobuf byte sequence
    		While parsing a protocol message, the input ended unexpectedly in the middle of a field.  This could mean either that the input has been truncated or that an embedded message misreported its own length.
    		iii. Protocol message contained an invalid tag (zero).
    

异常原因及解决方案:

原因

多线程同时向stream的observer句柄写数据,造成数据异常。

解决方案

observer加一个包装类,推送消息时使用包装类的推送方法,推送方法内加锁,使数据流能够顺序发送。类似于:

 public static class ObserverWrapper {
        @Getter
        private final String account;
        @Getter
        private final StreamObserver<Response> observer;

        private static final ReentrantLock LOCK = new ReentrantLock();

        public ObserverWrapper (String account, StreamObserver<Response> observer) {
            this.account = account;
            this.observer = observer;

            ((ServerCallStreamObserver) observer).setOnCancelHandler(() -> {
                LOG.error("通道关闭: {}", observer);
            });
        }

        public void sendMsg(List<Msg> list) {

            if (list== null || list.isEmpty()) {
                LOG.warn("推送信息为空......");
                return;
            }
            LOCK.lock();
            try {
                Response response = Response.newBuilder()
                        .addMsgs(list).build();
                this.observer.onNext(response);

                LOG.debug("向客户端: {}  信息成功: {}", account, list);
            } catch (Exception e) {
                LOG.error("发送消息异常", e);
            } finally {
                LOCK.unlock();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值