當前位置: 首頁>>代碼示例>>Java>>正文


Java EventLoop類代碼示例

本文整理匯總了Java中io.netty.channel.EventLoop的典型用法代碼示例。如果您正苦於以下問題:Java EventLoop類的具體用法?Java EventLoop怎麽用?Java EventLoop使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


EventLoop類屬於io.netty.channel包,在下文中一共展示了EventLoop類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: scheduleTimeout

import io.netty.channel.EventLoop; //導入依賴的package包/類
private <T> void scheduleTimeout(CompletableFuture<T> result, long timeoutMillis) {
    pendingFutures.add(result);
    if (isServerStopping()) {
        pendingFutures.remove(result);
        return;
    }

    final ScheduledFuture<?> timeoutFuture;
    if (timeoutMillis > 0) {
        final EventLoop eventLoop = RequestContext.current().eventLoop();
        timeoutFuture = eventLoop.schedule(() -> result.completeExceptionally(CANCELLATION_EXCEPTION),
                                           timeoutMillis, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    result.whenComplete((revision, cause) -> {
        if (timeoutFuture != null) {
            timeoutFuture.cancel(true);
        }
        pendingFutures.remove(result);
    });
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:24,代碼來源:WatchService.java

示例2: mapToThread

import io.netty.channel.EventLoop; //導入依賴的package包/類
private EventLoop mapToThread(int affinity, HandlerRegistration handler) {
    EventLoopGroup group;

    // Check if a dedicated thread pool is defined for this protocol.
    if (handler.config().getEventLoop() == null) {
        // Use core thread pool.
        group = coreEventLoopGroup;
    } else {
        // Use dedicated thread pool.
        group = handler.config().getEventLoop();
    }

    List<EventLoop> eventLoops = new ArrayList<>();

    // Assumes that the same group always returns its event loops in the same order.
    for (Iterator<EventExecutor> it = group.iterator(); it.hasNext(); ) {
        eventLoops.add((EventLoop)it.next());
    }

    return eventLoops.get(Utils.mod(affinity, eventLoops.size()));
}
 
開發者ID:hekate-io,項目名稱:hekate,代碼行數:22,代碼來源:NettyServerClient.java

示例3: runAtAllCost

import io.netty.channel.EventLoop; //導入依賴的package包/類
/**
 * Executes the task using the provided event loop or falls back to {@link AsyncUtils#fallbackExecutor()} if event loop is {@link
 * EventLoop#isShuttingDown() shut down}.
 *
 * @param eventLoop Event loop.
 * @param task Task.
 */
public static void runAtAllCost(EventLoop eventLoop, Runnable task) {
    assert eventLoop != null : "Event loop is null.";
    assert task != null : "Task is null.";

    boolean notified = false;

    // Try to execute via event loop.
    if (!eventLoop.isShuttingDown()) {
        try {
            eventLoop.execute(task);

            notified = true;
        } catch (RejectedExecutionException e) {
            // No-op.
        }
    }

    // If couldn't notify via event loop then use the fallback executor.
    if (!notified) {
        AsyncUtils.fallbackExecutor().execute(task);
    }
}
 
開發者ID:hekate-io,項目名稱:hekate,代碼行數:30,代碼來源:NettyUtils.java

示例4: operationComplete

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
    if (!channelFuture.isSuccess()) {
        channelFuture.channel().close();

        if (count.incrementAndGet() < MAX_RETRY) {
            final EventLoop loop = channelFuture.channel().eventLoop();

            loop.schedule(() -> {
                controller.connectRetry(this.ip, this.port, this);
            }, 1L, TimeUnit.SECONDS);
        } else {
            log.info("Connection to the ovsdb {}:{} failed",
                     this.ip.toString(), this.port.toString());
        }
    } else {
        handleNewNodeConnection(channelFuture.channel());
    }
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:20,代碼來源:Controller.java

示例5: AsyncCall

import io.netty.channel.EventLoop; //導入依賴的package包/類
/**
 * Constructor
 *
 * @param eventLoop           for call
 * @param connectId           connection id
 * @param md                  the method descriptor
 * @param param               parameters to send to Server
 * @param controller          controller for response
 * @param responseDefaultType the default response type
 */
public AsyncCall(EventLoop eventLoop, int connectId, Descriptors.MethodDescriptor md, Message
    param, PayloadCarryingRpcController controller, Message responseDefaultType,
    MetricsConnection.CallStats callStats) {
  super(eventLoop);

  this.id = connectId;

  this.method = md;
  this.param = param;
  this.controller = controller;
  this.responseDefaultType = responseDefaultType;

  this.startTime = EnvironmentEdgeManager.currentTime();
  this.rpcTimeout = controller.hasCallTimeout() ? controller.getCallTimeout() : 0;
  this.callStats = callStats;
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:27,代碼來源:AsyncCall.java

示例6: getCircuitBreaker

import io.netty.channel.EventLoop; //導入依賴的package包/類
protected Optional<CircuitBreaker<HttpResponse>> getCircuitBreaker(
    DownstreamRequestFirstChunkInfo downstreamReqFirstChunkInfo, ChannelHandlerContext ctx
) {
    if (downstreamReqFirstChunkInfo == null || downstreamReqFirstChunkInfo.disableCircuitBreaker)
        return Optional.empty();

    // Circuit breaking is enabled for this call. So we return the custom one specified or use the default one if a
    //      custom one is not specified.
    if (downstreamReqFirstChunkInfo.customCircuitBreaker.isPresent())
        return downstreamReqFirstChunkInfo.customCircuitBreaker;

    // No custom circuit breaker. Use the default for the given request's host.
    EventLoop nettyEventLoop = ctx.channel().eventLoop();
    CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(
        downstreamReqFirstChunkInfo.host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop)
    );
    return Optional.of(
        new CircuitBreakerDelegate<>(
            defaultStatusCodeCircuitBreaker,
            httpResponse -> (httpResponse == null ? null : httpResponse.getStatus().code())
        )
    );
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:24,代碼來源:ProxyRouterEndpointExecutionHandler.java

示例7: getCircuitBreaker

import io.netty.channel.EventLoop; //導入依賴的package包/類
protected Optional<CircuitBreaker<Response>> getCircuitBreaker(RequestBuilderWrapper requestBuilderWrapper) {
    if (requestBuilderWrapper.disableCircuitBreaker)
        return Optional.empty();

    // Circuit breaking is enabled for this call. So we return the custom one specified or use the default one if a
    //      custom one is not specified.
    if (requestBuilderWrapper.customCircuitBreaker.isPresent())
        return requestBuilderWrapper.customCircuitBreaker;

    // No custom circuit breaker. Use the default for the given request's host.
    Uri uri = Uri.create(requestBuilderWrapper.url);
    String host = uri.getHost();
    EventLoop nettyEventLoop = requestBuilderWrapper.getCtx() == null
                               ? null
                               : requestBuilderWrapper.getCtx().channel().eventLoop();
    CircuitBreaker<Integer> defaultStatusCodeCircuitBreaker = getDefaultHttpStatusCodeCircuitBreakerForKey(
        host, Optional.ofNullable(nettyEventLoop), Optional.ofNullable(nettyEventLoop)
    );
    return Optional.of(
        new CircuitBreakerDelegate<>(
            defaultStatusCodeCircuitBreaker, response -> (response == null ? null : response.getStatusCode())
        )
    );
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:25,代碼來源:AsyncHttpClientHelper.java

示例8: beforeMethod

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Before
public void beforeMethod() {
    helperSpy = spy(new AsyncHttpClientHelper());
    channelMock = mock(Channel.class);
    ctxMock = mock(ChannelHandlerContext.class);
    stateAttributeMock = mock(Attribute.class);
    state = new HttpProcessingState();
    eventLoopMock = mock(EventLoop.class);
    signatureCalculator = mock(SignatureCalculator.class);
    doReturn(channelMock).when(ctxMock).channel();
    doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY);
    doReturn(state).when(stateAttributeMock).get();
    doReturn(eventLoopMock).when(channelMock).eventLoop();

    handlerWithTracingAndMdcDummyExample = new AsyncCompletionHandlerWithTracingAndMdcSupport<>(
        null, null, false, null, null, null, null, null
    );

    resetTracingAndMdc();
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:21,代碼來源:AsyncHttpClientHelperTest.java

示例9: dispatch

import io.netty.channel.EventLoop; //導入依賴的package包/類
/**
 * Dispatches an AddressedMessage to its target handler using an EventExecutor.
 *
 * @param msg AddressedMessage to dispatch.
 * @return {@code true} if the Message was forwarded to at least one MessageHandler.
 */
public boolean dispatch(final Message.AddressedMessage msg) {
    Set<MessageHandler> handlers = mappings.get(RoutingKey.forMessage(msg));
    final EventLoop executor = getEventLoop();
    Log.v(TAG, "DISPATCH " + msg + " to " + handlers + " using " + executor);
    for (final MessageHandler handler : handlers) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    handler.handle(msg);
                } catch (Exception e) {
                    Log.e(TAG, "Handler " + handler + " crashed while handling message " + msg
                            + " with Exception " + Log.getStackTraceString(e));
                }
            }
        });
    }
    return !handlers.isEmpty();
}
 
開發者ID:SecureSmartHome,項目名稱:SecureSmartHome,代碼行數:26,代碼來源:IncomingDispatcher.java

示例10: channelInactive

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    LOG.info(">>> channelUnregistered");
    if (unrecognizedName) {
        LOG.info(">>> unrecognizedName retry");
        final EventLoop loop = ctx.channel().eventLoop();
        loop.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    client.retry(loop);
                } catch (InterruptedException e) {
                    LOG.info(">>> retry interrupted, shutdown");
                    client.stop();
                }
            }
        });
    } else {
        LOG.info(">>> shutdown sucessfully");
        client.stop();
    }
}
 
開發者ID:wxyzZ,項目名稱:little_mitm,代碼行數:23,代碼來源:RetryClient.java

示例11: addAsync

import io.netty.channel.EventLoop; //導入依賴的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;
}
 
開發者ID:rollenholt-SourceReading,項目名稱:redisson,代碼行數:19,代碼來源:RedissonSortedSet.java

示例12: shutdownOutput

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Override
public ChannelFuture shutdownOutput(final ChannelPromise future) {
    EventLoop loop = eventLoop();
    if (loop.inEventLoop()) {
        try {
            socket.shutdownOutput();
            future.setSuccess();
        } catch (Throwable t) {
            future.setFailure(t);
        }
    } else {
        loop.execute(new Runnable() {
            @Override
            public void run() {
                shutdownOutput(future);
            }
        });
    }
    return future;
}
 
開發者ID:wuyinxian124,項目名稱:netty4.0.27Learn,代碼行數:21,代碼來源:OioSocketChannel.java

示例13: shutdownOutput

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Override
public ChannelFuture shutdownOutput(final ChannelPromise promise) {
    Executor closeExecutor = ((NioSocketChannelUnsafe) unsafe()).closeExecutor();
    if (closeExecutor != null) {
        closeExecutor.execute(new OneTimeTask() {
            @Override
            public void run() {
                shutdownOutput0(promise);
            }
        });
    } else {
        EventLoop loop = eventLoop();
        if (loop.inEventLoop()) {
            shutdownOutput0(promise);
        } else {
            loop.execute(new OneTimeTask() {
                @Override
                public void run() {
                    shutdownOutput0(promise);
                }
            });
        }
    }
    return promise;
}
 
開發者ID:wuyinxian124,項目名稱:netty4.0.27Learn,代碼行數:26,代碼來源:NioSocketChannel.java

示例14: clearEpollIn

import io.netty.channel.EventLoop; //導入依賴的package包/類
final void clearEpollIn() {
    // Only clear if registered with an EventLoop as otherwise
    if (isRegistered()) {
        final EventLoop loop = eventLoop();
        final AbstractEpollUnsafe unsafe = (AbstractEpollUnsafe) unsafe();
        if (loop.inEventLoop()) {
            unsafe.clearEpollIn0();
        } else {
            // schedule a task to clear the EPOLLIN as it is not safe to modify it directly
            loop.execute(new OneTimeTask() {
                @Override
                public void run() {
                    if (!config().isAutoRead() && !unsafe.readPending) {
                        // Still no read triggered so clear it now
                        unsafe.clearEpollIn0();
                    }
                }
            });
        }
    } else  {
        // The EventLoop is not registered atm so just update the flags so the correct value
        // will be used once the channel is registered
        flags &= ~readFlag;
    }
}
 
開發者ID:wuyinxian124,項目名稱:netty4.0.27Learn,代碼行數:26,代碼來源:AbstractEpollChannel.java

示例15: shutdownOutput

import io.netty.channel.EventLoop; //導入依賴的package包/類
@Override
public ChannelFuture shutdownOutput(final ChannelPromise promise) {
    Executor closeExecutor = ((EpollSocketChannelUnsafe) unsafe()).closeExecutor();
    if (closeExecutor != null) {
        closeExecutor.execute(new OneTimeTask() {
            @Override
            public void run() {
                shutdownOutput0(promise);
            }
        });
    } else {
        EventLoop loop = eventLoop();
        if (loop.inEventLoop()) {
            shutdownOutput0(promise);
        } else {
            loop.execute(new OneTimeTask() {
                @Override
                public void run() {
                    shutdownOutput0(promise);
                }
            });
        }
    }
    return promise;
}
 
開發者ID:wuyinxian124,項目名稱:netty4.0.27Learn,代碼行數:26,代碼來源:EpollSocketChannel.java


注:本文中的io.netty.channel.EventLoop類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。