在用springcloud开发过程中对netty开发的websocket进行心跳超时设置,开始设置的时间是10分钟,超时就断开,发现部署到dev环境中,还是1分钟没有消息交互,准时断开连接。最后调试发现是nginx超时断开了,于是在nginx加入配置。
netty心跳超时设置
pipeline.addLast(new IdleStateHandler(properties.getReadTimeout(), properties.getWriteTimeout(), properties.getAllTimeout(), TimeUnit.SECONDS));
pipeline.addLast(new HeartbeatServerHandler());
@Slf4j
public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter {
// Return a unreleasable view on the given ByteBuf
// which will just ignore release and retain calls.
private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat", CharsetUtil.UTF_8)); // 1
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) { // 2
IdleStateEvent event = (IdleStateEvent) evt;
String type = "";
if (event.state() == IdleState.READER_IDLE) {
type = "read idle";
} else if (event.state() == IdleState.WRITER_IDLE) {
type = "write idle";
} else if (event.state() == IdleState.ALL_IDLE) {
type = "all idle";
}
ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); // 3
log.info("===>>> client timeout type: {}, address: ", type, ctx.channel().remoteAddress());
} else {
super.userEventTriggered(ctx, evt);
}
}
}
nginx配置
设置keepalive_timeout无效,这里是用nginx代理的wss服务。所以需要使用proxy_..._timeout配置。
http{
proxy_read_timeout 600;
proxy_send_timeout 600;
...
}
网友评论