CONNECT_TIMEOUT_MILLIS

  • 属于 SocketChannal 参数
  • 用在客户端建立连接时,如果在指定毫秒内无法连接,会抛出 timeout 异常
  • SO_TIMEOUT 主要用在阻塞 IO,阻塞 IO 中 accept,read 等都是无限等待的,如果不希望永远阻塞,使用它调整超时时间
  1. @Slf4j
  2. public class TestConnectionTimeout {
  3. public static void main(String[] args) {
  4. NioEventLoopGroup group = new NioEventLoopGroup();
  5. try {
  6. Bootstrap bootstrap = new Bootstrap()
  7. .group(group)
  8. .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 300)
  9. .channel(NioSocketChannel.class)
  10. .handler(new LoggingHandler());
  11. ChannelFuture future = bootstrap.connect("127.0.0.1", 8080);
  12. future.sync().channel().closeFuture().sync(); // 断点1
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. log.debug("timeout");
  16. } finally {
  17. group.shutdownGracefully();
  18. }
  19. }
  20. }

另外源码部分 io.netty.channel.nio.AbstractNioChannel.AbstractNioUnsafe#connect

  1. @Override
  2. public final void connect(
  3. final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) {
  4. // ...
  5. // Schedule connect timeout.
  6. int connectTimeoutMillis = config().getConnectTimeoutMillis();
  7. if (connectTimeoutMillis > 0) {
  8. connectTimeoutFuture = eventLoop().schedule(new Runnable() {
  9. @Override
  10. public void run() {
  11. ChannelPromise connectPromise = AbstractNioChannel.this.connectPromise;
  12. ConnectTimeoutException cause =
  13. new ConnectTimeoutException("connection timed out: " + remoteAddress); // 断点2
  14. if (connectPromise != null && connectPromise.tryFailure(cause)) {
  15. close(voidPromise());
  16. }
  17. }
  18. }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
  19. }
  20. // ...
  21. }