本文整理匯總了Java中io.netty.util.concurrent.Promise類的典型用法代碼示例。如果您正苦於以下問題:Java Promise類的具體用法?Java Promise怎麽用?Java Promise使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Promise類屬於io.netty.util.concurrent包,在下文中一共展示了Promise類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: propagateResponse
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
private synchronized void propagateResponse(Chunk chunk) {
ChunkRequest chunkRequest = chunkRequestMap.get(chunk.getKey());
for (Promise<Chunk> localRequester : chunkRequest.localRequesters) {
localRequester.setSuccess(chunk);
}
for (Map.Entry<Long, Collection<BzzRetrieveReqMessage>> e :
chunkRequest.requesters.entrySet()) {
BzzStoreReqMessage msg = new BzzStoreReqMessage(e.getKey(), chunk.getKey(), chunk.getData());
int counter = requesterCount;
for (BzzRetrieveReqMessage r : e.getValue()) {
r.getPeer().sendMessage(msg);
statOutStoreReq.add(1);
if (--counter < 0) {
break;
}
}
}
}
示例2: getConnection
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
@Override
public Future<Channel> getConnection(HostAndPort address)
{
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.option(CONNECT_TIMEOUT_MILLIS, saturatedCast(connectTimeout.toMillis()))
.handler(new ThriftClientInitializer(
messageFraming,
messageEncoding,
requestTimeout,
socksProxy,
sslContextSupplier));
Promise<Channel> promise = group.next().newPromise();
bootstrap.connect(new InetSocketAddress(address.getHost(), address.getPort()))
.addListener((ChannelFutureListener) future -> notifyConnect(future, promise));
return promise;
}
catch (Throwable e) {
return group.next().newFailedFuture(new TTransportException(e));
}
}
示例3: channelRead0
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, ResponseWrapper msg) throws Exception {
//找到對應的client請求, 給請求設置promise為true,然後給請求設置值
Promise<ResponseWrapper> responsePromise = RpcClient.getRequestWrapperMap().get(msg.getRequestId());
if (responsePromise != null) {
if (msg.getStatus() == 200) {
responsePromise.setSuccess(msg);
} else {
System.out.println("error: " + msg.getStatus());
//設置錯誤!
}
//設置完畢之後就可以移出map了
RpcClient.getRequestWrapperMap().remove(msg.getRequestId());
} else {
System.out.println("requestWrapper not found");
}
}
示例4: channelRead0
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg)
throws Exception {
Integer streamId =
msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
if (streamId == null) {
System.err.println("HttpResponseHandler unexpected message received: "
+ msg);
return;
}
if (streamId.intValue() == 1) {
// this is the upgrade response message, just ignore it.
return;
}
Promise<FullHttpResponse> promise;
synchronized (this) {
promise = streamId2Promise.get(streamId);
}
if (promise == null) {
System.err.println("Message received for unknown stream id " + streamId);
} else {
// Do stuff with the message (for now just print it)
promise.setSuccess(msg.retain());
}
}
示例5: test
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
@Test
public void test() throws InterruptedException, ExecutionException {
int streamId = 3;
FullHttpRequest request =
new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
request.headers().add(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(),
streamId);
Promise<FullHttpResponse> promise = CHANNEL.eventLoop().newPromise();
synchronized (RESPONSE_HANDLER) {
CHANNEL.writeAndFlush(request);
RESPONSE_HANDLER.put(streamId, promise);
}
assertEquals(HttpResponseStatus.OK, promise.get().status());
ByteBuf content = promise.get().content();
assertEquals("HTTP/2 DTP", content.toString(StandardCharsets.UTF_8));
}
示例6: shutdown
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
/**
* Disconnect from the AudioConnect server and shutdown this client.<br>
* If this client has already been or is being shutdown, this will do nothing.<br>
* <b>Note:</b> This client instance will no longer be able to connect after this is called.
* @return a Future for when this client has completely disconnected and been shutdown.
*/
public Future<?> shutdown() {
if (bootstrap.group().isShuttingDown()) {
return GlobalEventExecutor.INSTANCE.newSucceededFuture(null);
}
final Promise<Object> shutdownPromise = GlobalEventExecutor.INSTANCE.newPromise();
disconnect().addListener(new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) {
bootstrap.group().shutdownGracefully().addListener(new PromiseNotifier<>(shutdownPromise));
}
});
return shutdownPromise;
}
示例7: initBootStrap
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
protected Bootstrap initBootStrap(Promise<Channel> promise, EventLoopGroup eventLoopGroup) {
return new Bootstrap()
.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, NettySettings.CONNECT_TIMEOUT)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ProxyHandler proxyHandler = proxyHandlerSupplier.get();
if (proxyHandler != null) {
ch.pipeline().addLast(proxyHandler);
}
ch.pipeline().addLast(new ChannelActiveAwareHandler(promise));
}
});
}
示例8: runRoundTripTests
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
private void runRoundTripTests(BlockingQueue<Object> serverQueue, BlockingQueue<Object> clientQueue,
Promise<SocketChannel> serverChannel, Promise<SocketChannel> clientChannel)
throws InterruptedException, ExecutionException {
String obj1 = "test123ÄÖÜ∑";
clientChannel.get().writeAndFlush(obj1).await(1000);
assertEquals(obj1, serverQueue.poll(1000, TimeUnit.MILLISECONDS));
Map<String, Object> obj2 = new HashMap<>();
obj2.put("test", "abc");
obj2.put("test2", 123);
obj2.putAll(System.getenv());
serverChannel.get().writeAndFlush(obj2).await(1000);
assertEquals(obj2, clientQueue.poll(1000, TimeUnit.MILLISECONDS));
SecretKey obj3 = new SecretKeySpec(new byte[]{1, 2, 3, 4}, "RAW");
clientChannel.get().writeAndFlush(obj3).await(1000);
assertEquals(obj3, serverQueue.poll(1000, TimeUnit.MILLISECONDS));
}
示例9: disconnect
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
/**
* Disconnects. This will wait for pending writes to be flushed before
* disconnecting.
*
* @return Future<Void> for when we're done disconnecting. If we weren't
* connected, this returns null.
*/
Future<Void> disconnect() {
if (channel == null) {
return null;
} else {
final Promise<Void> promise = channel.newPromise();
writeToChannel(Unpooled.EMPTY_BUFFER).addListener(
new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(
Future<? super Void> future)
throws Exception {
closeChannel(promise);
}
});
return promise;
}
}
示例10: closeChannel
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
private void closeChannel(final Promise<Void> promise) {
channel.close().addListener(
new GenericFutureListener<Future<? super Void>>() {
public void operationComplete(
Future<? super Void> future)
throws Exception {
if (future
.isSuccess()) {
promise.setSuccess(null);
} else {
promise.setFailure(future
.cause());
}
};
});
}
示例11: channelActive
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
/**
* Write <hello> to the server after SSL handshake completion to request <greeting>
*
* <p>When handling EPP over TCP, the server should issue a <greeting> to the client when a
* connection is established. Nomulus app however does not automatically sends the <greeting> upon
* connection. The proxy therefore first sends a <hello> to registry to request a <greeting>
* response.
*
* <p>The <hello> request is only sent after SSL handshake is completed between the client and the
* proxy so that the client certificate hash is available, which is needed to communicate with the
* server. Because {@link SslHandshakeCompletionEvent} is triggered before any calls to {@link
* #channelRead} are scheduled by the event loop executor, the <hello> request is guaranteed to be
* the first message sent to the server.
*
* @see <a href="https://tools.ietf.org/html/rfc5734">RFC 5732 EPP Transport over TCP</a>
* @see <a href="https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt">The Proxy
* Protocol</a>
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Promise<X509Certificate> unusedPromise =
ctx.channel()
.attr(CLIENT_CERTIFICATE_PROMISE_KEY)
.get()
.addListener(
(Promise<X509Certificate> promise) -> {
if (promise.isSuccess()) {
sslClientCertificateHash = getCertificateHash(promise.get());
// Set the client cert hash key attribute for both this channel,
// used for collecting metrics on specific clients.
ctx.channel().attr(CLIENT_CERTIFICATE_HASH_KEY).set(sslClientCertificateHash);
clientAddress = ctx.channel().attr(REMOTE_ADDRESS_KEY).get();
metrics.registerActiveConnection(
"epp", sslClientCertificateHash, ctx.channel());
channelRead(ctx, Unpooled.wrappedBuffer(helloBytes));
} else {
logger.severefmt(promise.cause(), "Cannot finish handshake.");
ChannelFuture unusedFuture = ctx.close();
}
});
super.channelActive(ctx);
}
示例12: async
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
@Override
protected <V, R> void async(boolean readOnlyMode, int slot, MultiDecoder<Object> messageDecoder,
Codec codec, RedisCommand<V> command, Object[] params, Promise<R> mainPromise, int attempt) {
if (executed) {
throw new IllegalStateException("Batch already executed!");
}
Entry entry = commands.get(slot);
if (entry == null) {
entry = new Entry();
Entry oldEntry = commands.putIfAbsent(slot, entry);
if (oldEntry != null) {
entry = oldEntry;
}
}
if (!readOnlyMode) {
entry.setReadOnlyMode(false);
}
entry.getCommands().add(new CommandEntry(new CommandData<V, R>(mainPromise, messageDecoder, codec, command, params), index.incrementAndGet()));
}
示例13: connectAsync
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
public Future<RedisConnection> connectAsync() {
final Promise<RedisConnection> f = bootstrap.group().next().newPromise();
ChannelFuture channelFuture = bootstrap.connect();
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
RedisConnection c = new RedisConnection(RedisClient.this, future.channel());
f.setSuccess(c);
} else {
f.setFailure(future.cause());
}
}
});
return f;
}
示例14: retryReadRandomAsync
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final Promise<R> mainPromise,
final List<Integer> slots, final Object... params) {
final Promise<R> attemptPromise = connectionManager.newPromise();
attemptPromise.addListener(new FutureListener<R>() {
@Override
public void operationComplete(Future<R> future) throws Exception {
if (future.isSuccess()) {
if (future.getNow() == null) {
if (slots.isEmpty()) {
mainPromise.setSuccess(null);
} else {
retryReadRandomAsync(command, mainPromise, slots, params);
}
} else {
mainPromise.setSuccess(future.getNow());
}
} else {
mainPromise.setFailure(future.cause());
}
}
});
Integer slot = slots.remove(0);
async(true, slot, null, connectionManager.getCodec(), command, params, attemptPromise, 0);
}
示例15: addAsync
import io.netty.util.concurrent.Promise; //導入依賴的package包/類
public Future<Boolean> addAsync(final V value) {
EventLoop loop = commandExecutor.getConnectionManager().getGroup().next();
final Promise<Boolean> promise = loop.newPromise();
loop.execute(new Runnable() {
@Override
public void run() {
try {
boolean result = add(value);
promise.setSuccess(result);
} catch (Exception e) {
promise.setFailure(e);
}
}
});
return promise;
}