Reactor Netty IdleStateHandler 作为保活机制中断 http2 连接

问题描述 投票:0回答:0

我正在使用 Netty 的 IdleStateHandler 来保持长期存在的 SSE 连接:

public final class NettyKeepAliveCustomizer implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {

    private final SseKeepAliveConfiguration configuration;
    private static final String DATA = "\n";

    @Override
    public void customize(NettyReactiveWebServerFactory factory) {
        factory.addServerCustomizers(builder -> builder.doOnChannelInit((connectionObserver, channel, remoteAddress) -> {
            final ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new IdleStateHandler(configuration.getReaderIdle(),
                    configuration.getWriterIdle(),
                    configuration.getAllIdle()));
            pipeline.addLast(new IdleHandler());
        }));
    }


    private static final class IdleHandler extends ChannelDuplexHandler {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent e) {
                if (e.state() == IdleState.WRITER_IDLE) {
                    final ByteBuf byteBufMsg = ctx.alloc().buffer(DATA.length());
                    byteBufMsg.writeBytes(DATA.getBytes(StandardCharsets.UTF_8));
                    ctx.writeAndFlush(byteBufMsg);
                }
            }
            super.userEventTriggered(ctx, evt);
        }
    }
}

如果我尝试在几次空闲状态迭代(写入几个数据包)后将一些数据写入 SSE 流,连接会因某种原因中断。这仅在启用 HTTP2 时发生,因此我认为这可能与未针对 HTTP2 正确编码的数据有关。请帮我找到解决方案。

java spring-webflux netty project-reactor http2
© www.soinside.com 2019 - 2024. All rights reserved.