io.netty.util.concurrent.Promise类的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(291)

本文整理了Java中io.netty.util.concurrent.Promise类的一些代码示例,展示了Promise类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Promise类的具体详情如下:
包路径:io.netty.util.concurrent.Promise
类名称:Promise

Promise介绍

[英]Special Future which is writable.
[中]特殊的未来是可写的。

代码示例

代码示例来源:origin: netty/netty

@Override
  public void operationComplete(Future<Void> future) throws Exception {
    assert executor.inEventLoop();
    if (closed) {
      // Since the pool is closed, we have no choice but to close the channel
      channel.close();
      promise.setFailure(POOL_CLOSED_ON_RELEASE_EXCEPTION);
      return;
    }
    if (future.isSuccess()) {
      decrementAndRunTaskQueue();
      promise.setSuccess(null);
    } else {
      Throwable cause = future.cause();
      // Check if the exception was not because of we passed the Channel to the wrong pool.
      if (!(cause instanceof IllegalArgumentException)) {
        decrementAndRunTaskQueue();
      }
      promise.setFailure(future.cause());
    }
  }
}));

代码示例来源:origin: redisson/redisson

private void applyHandshakeTimeout() {
  final Promise<Channel> localHandshakePromise = this.handshakePromise;
  // Set timeout if necessary.
  final long handshakeTimeoutMillis = this.handshakeTimeoutMillis;
  if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
    return;
  }
  final ScheduledFuture<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
    @Override
    public void run() {
      if (localHandshakePromise.isDone()) {
        return;
      }
      try {
        if (localHandshakePromise.tryFailure(HANDSHAKE_TIMED_OUT)) {
          SslUtils.handleHandshakeFailure(ctx, HANDSHAKE_TIMED_OUT, true);
        }
      } finally {
        releaseAndFailAll(HANDSHAKE_TIMED_OUT);
      }
    }
  }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
  // Cancel the handshake timeout when handshake is finished.
  localHandshakePromise.addListener(new FutureListener<Channel>() {
    @Override
    public void operationComplete(Future<Channel> f) throws Exception {
      timeoutFuture.cancel(false);
    }
  });
}

代码示例来源:origin: netty/netty

private void notifyConnect(ChannelFuture future, Promise<Channel> promise) {
  if (future.isSuccess()) {
    Channel channel = future.channel();
    if (!promise.trySuccess(channel)) {
      // Promise was completed in the meantime (like cancelled), just release the channel again
      release(channel);
    }
  } else {
    promise.tryFailure(future.cause());
  }
}

代码示例来源:origin: netty/netty

private boolean tryPromise() {
  return (cause == null) ? aggregatePromise.trySuccess(null) : aggregatePromise.tryFailure(cause);
}

代码示例来源:origin: netty/netty

@Override
protected void doResolve(String inetHost, Promise<InetAddress> promise) throws Exception {
  try {
    promise.setSuccess(SocketUtils.addressByName(inetHost));
  } catch (UnknownHostException e) {
    promise.setFailure(e);
  }
}

代码示例来源:origin: netty/netty

@Override
  public void operationComplete(Future<InetAddress> future) throws Exception {
    if (future.isSuccess()) {
      promise.setSuccess(new InetSocketAddress(future.getNow(), unresolvedAddress.getPort()));
    } else {
      promise.setFailure(future.cause());
    }
  }
});

代码示例来源:origin: wildfly/wildfly

public void open0(ChannelHandlerContext ctx, final Promise<Http2StreamChannel> promise) {
  assert ctx.executor().inEventLoop();
  final Http2StreamChannel streamChannel = ((Http2MultiplexCodec) ctx.handler()).newOutboundStream();
  try {
    init(streamChannel);
  } catch (Exception e) {
    streamChannel.unsafe().closeForcibly();
    promise.setFailure(e);
    return;
  }
  ChannelFuture future = ctx.channel().eventLoop().register(streamChannel);
  future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        promise.setSuccess(streamChannel);
      } else if (future.isCancelled()) {
        promise.cancel(false);
      } else {
        if (streamChannel.isRegistered()) {
          streamChannel.close();
        } else {
          streamChannel.unsafe().closeForcibly();
        }
        promise.setFailure(future.cause());
      }
    }
  });
}

代码示例来源:origin: line/armeria

private void initSession(SessionProtocol desiredProtocol, ChannelFuture connectFuture,
             Promise<Channel> sessionPromise) {
  assert connectFuture.isSuccess();
  final Channel ch = connectFuture.channel();
  final EventLoop eventLoop = ch.eventLoop();
  assert eventLoop.inEventLoop();
  final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> {
    if (sessionPromise.tryFailure(new SessionProtocolNegotiationException(
        desiredProtocol, "connection established, but session creation timed out: " + ch))) {
      ch.close();
    }
  }, connectTimeoutMillis, TimeUnit.MILLISECONDS);
  ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture));
}

代码示例来源:origin: com.simplyti.cloud/simple-server-core

private Future<Void> bind(EventLoop executor, int port) {
  Promise<Void> futureBind = executor.newPromise();
  log.info("Starting service listener on port {}", port);
  ChannelFuture channelFuture = bootstrap.bind(port);
  channelFuture.addListener((ChannelFuture future) -> {
    if (future.isSuccess()) {
      log.info("Listening on {}", future.channel().localAddress());
      this.serverChannels.add(channelFuture.channel());
      futureBind.setSuccess(null);
    } else {
      log.warn("Error listening on port {}: {}", port, future.cause().getMessage());
      futureBind.setFailure(future.cause());
    }
  });
  return futureBind;
}

代码示例来源:origin: org.apache.jackrabbit/oak-tarmk-standby

@Override
  @Deprecated
  public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
      promise.setFailure(future.cause());
      future.channel().close();
    } else {
      future.channel().read();
    }
  }
}

代码示例来源:origin: netty/netty

bs.attr(POOL_KEY, this);
  ChannelFuture f = connectChannel(bs);
  if (f.isDone()) {
    notifyConnect(f, promise);
  } else {
    f.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
EventLoop loop = ch.eventLoop();
if (loop.inEventLoop()) {
  doHealthCheck(ch, promise);
} else {
  loop.execute(new Runnable() {
    @Override
    public void run() {
promise.tryFailure(cause);

代码示例来源:origin: linkedin/flashback

private void closeChannel(final Promise<Void> promise, final Channel channel) {
  channel.close().addListener(future -> {
   if (future.isSuccess()) {
    promise.setSuccess(null);
   } else {
    promise.setFailure(future.cause());
   }
  });
 }
}

代码示例来源:origin: redisson/redisson

private void readIfNeeded(ChannelHandlerContext ctx) {
  // If handshake is not finished yet, we need more data.
  if (!ctx.channel().config().isAutoRead() && (!firedChannelRead || !handshakePromise.isDone())) {
    // No auto-read used and no message passed through the ChannelPipeline or the handshake was not complete
    // yet, which means we need to trigger the read to ensure we not encounter any stalls.
    ctx.read();
  }
}

代码示例来源:origin: Netflix/zuul

promise = origin.connectToOrigin(zuulRequest, channelCtx.channel().eventLoop(), attemptNum, passport, chosenServer, chosenHostAddr);
passport.add(PassportState.ORIGIN_CONN_ACQUIRE_START);
if (promise.isDone()) {
  operationComplete(promise);
} else {
  promise.addListener(this);
LOG.error("Error while connecting to origin, UUID {} " + context.getUUID(), ex);
storeAndLogOriginRequestInfo();
if (promise != null && ! promise.isDone()) {
  promise.setFailure(ex);
} else {
  errorFromOrigin(ex);

代码示例来源:origin: redisson/redisson

/**
 * Notify all the handshake futures about the successfully handshake
 */
private void setHandshakeSuccess() {
  handshakePromise.trySuccess(ctx.channel());
  if (logger.isDebugEnabled()) {
    logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite());
  }
  ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
  if (readDuringHandshake && !ctx.channel().config().isAutoRead()) {
    readDuringHandshake = false;
    ctx.read();
  }
}

代码示例来源:origin: wildfly/wildfly

public Future<Http2StreamChannel> open(final Promise<Http2StreamChannel> promise) {
  final ChannelHandlerContext ctx = channel.pipeline().context(Http2MultiplexCodec.class);
  if (ctx == null) {
    if (channel.isActive()) {
      promise.setFailure(new IllegalStateException(StringUtil.simpleClassName(Http2MultiplexCodec.class) +
          " must be in the ChannelPipeline of Channel " + channel));
    } else {
      promise.setFailure(new ClosedChannelException());
    }
  } else {
    EventExecutor executor = ctx.executor();
    if (executor.inEventLoop()) {
      open0(ctx, promise);
    } else {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          open0(ctx, promise);
        }
      });
    }
  }
  return promise;
}

代码示例来源:origin: netty/netty

private void notifyHealthCheck(Future<Boolean> future, Channel ch, Promise<Channel> promise) {
  assert ch.eventLoop().inEventLoop();
  if (future.isSuccess()) {
    if (future.getNow()) {
      try {
        ch.attr(POOL_KEY).set(this);
        handler.channelAcquired(ch);
        promise.setSuccess(ch);
      } catch (Throwable cause) {
        closeAndFail(ch, cause, promise);
      }
    } else {
      closeChannel(ch);
      acquireHealthyFromPoolOrNew(promise);
    }
  } else {
    closeChannel(ch);
    acquireHealthyFromPoolOrNew(promise);
  }
}

代码示例来源:origin: Netflix/zuul

protected void createConnection(ChannelFuture cf, Promise<PooledConnection> callerPromise, String httpMethod, String uri,
                int attemptNum, CurrentPassport passport) {
  final PooledConnection conn = pooledConnectionFactory.create(cf.channel());
  conn.incrementUsageCount();
  conn.startRequestTimer();
  conn.getChannel().read();
  onAcquire(conn, httpMethod, uri, attemptNum, passport);
  callerPromise.setSuccess(conn);
}

代码示例来源:origin: redisson/redisson

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
  super.channelActive(ctx);
  channelActivePromise.setSuccess(ctx.channel());
}

代码示例来源:origin: netty/netty

public static <X> void cascadeTo(Future<X> completedFuture, Promise<? super X> promise) {
    if (completedFuture.isSuccess()) {
      if (!promise.trySuccess(completedFuture.getNow())) {
        logger.warn("Failed to mark a promise as success because it is done already: {}", promise);
      }
    } else if (completedFuture.isCancelled()) {
      if (!promise.cancel(false)) {
        logger.warn("Failed to cancel a promise because it is done already: {}", promise);
      }
    } else {
      if (!promise.tryFailure(completedFuture.cause())) {
        logger.warn("Failed to mark a promise as failure because it's done already: {}", promise,
              completedFuture.cause());
      }
    }
  }
}

相关文章