Java Code Examples for io.netty.util.concurrent.GlobalEventExecutor#INSTANCE

The following examples show how to use io.netty.util.concurrent.GlobalEventExecutor#INSTANCE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProxyConnectorFactory.java    From styx with Apache License 2.0 6 votes vote down vote up
private ProxyConnector(ConnectorConfig config, ProxyConnectorFactory factory) {
    this.config = requireNonNull(config);
    this.responseEnhancer = requireNonNull(factory.responseEnhancer);
    this.serverConfig = requireNonNull(factory.serverConfig);
    this.metrics = requireNonNull(factory.metrics);
    this.httpErrorStatusListener = requireNonNull(factory.errorStatusListener);
    this.channelStatsHandler = new ChannelStatisticsHandler(metrics);
    this.requestStatsCollector = new RequestStatsCollector(metrics.scope("requests"));
    this.excessConnectionRejector = new ExcessConnectionRejector(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), serverConfig.maxConnectionsCount());
    this.unwiseCharEncoder = new ConfigurableUnwiseCharsEncoder(factory.unwiseCharacters);
    if (isHttps()) {
        this.sslContext = Optional.of(newSSLContext((HttpsConnectorConfig) config, metrics));
    } else {
        this.sslContext = Optional.empty();
    }
    this.requestTracker = factory.requestTracking ? CurrentRequestTracker.INSTANCE : RequestTracker.NO_OP;
    this.httpMessageFormatter = factory.httpMessageFormatter;
    this.originsHeader = factory.originsHeader;
}
 
Example 2
Source File: NettyServer.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("stopping netty server");

            bossGroup.shutdownGracefully();
            bossGroup = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            allChannels.add(serverChannel);
            for (Channel ch : conns.values()) {
                allChannels.add(ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("netty server stopped");
        }
    }
 
Example 3
Source File: PlatformSSLClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public void disconnect() {
	// logger.info("close tcp socket, Disconnecting.");
	synchronized (this.clientBoot) {
		this.channelPromise = null;
		final Future<Void> channelCloseFuture;
		if (this.channelPromise != null) {
			channelCloseFuture = this.channelPromise.channel().close();
		} else {
			channelCloseFuture = new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null);
		}
		channelCloseFuture.addListener(new GenericFutureListener<Future<Void>>() {
			@Override
			public void operationComplete(final Future<Void> future) throws Exception {
				PlatformSSLClient.this.clientBoot.config().group().shutdownGracefully();
			}
		});
	}
	// logger.info("close netty tcp socket connection");
}
 
Example 4
Source File: Http2FrameCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void newOutboundStream() {
    final Http2FrameStream stream = frameCodec.newStream();

    assertNotNull(stream);
    assertFalse(isStreamIdValid(stream.id()));

    final Promise<Void> listenerExecuted = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE);

    channel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false).stream(stream))
           .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    assertTrue(future.isSuccess());
                    assertTrue(isStreamIdValid(stream.id()));
                    listenerExecuted.setSuccess(null);
                }
            }
    );
    ByteBuf data = Unpooled.buffer().writeZero(100);
    ChannelFuture f = channel.writeAndFlush(new DefaultHttp2DataFrame(data).stream(stream));
    assertTrue(f.isSuccess());

    listenerExecuted.syncUninterruptibly();
    assertTrue(listenerExecuted.isSuccess());
}
 
Example 5
Source File: CatNettyClient.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("cat stopping netty client");

            timer.cancel();
            timer = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            for (Object ch : conns.values()) {
                if (ch != null && ch != dummyChannel)
                    allChannels.add((Channel) ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("cat netty client stopped");
        }
    }
 
Example 6
Source File: ThreadPerChannelEventLoopGroupTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTerminationFutureSuccessReflectively() throws Exception {
    Field terminationFutureField =
            ThreadPerChannelEventLoopGroup.class.getDeclaredField("terminationFuture");
    terminationFutureField.setAccessible(true);
    final Exception[] exceptionHolder = new Exception[1];
    for (int i = 0; i < 2; i++) {
        ThreadPerChannelEventLoopGroup loopGroup = new ThreadPerChannelEventLoopGroup(64);
        Promise<?> promise = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE) {
            @Override
            public Promise<Void> setSuccess(Void result) {
                try {
                    return super.setSuccess(result);
                } catch (IllegalStateException e) {
                    exceptionHolder[0] = e;
                    throw e;
                }
            }
        };
        terminationFutureField.set(loopGroup, promise);
        runTest(loopGroup);
    }
    // The global event executor will not terminate, but this will give the test a chance to fail.
    GlobalEventExecutor.INSTANCE.awaitTermination(100, TimeUnit.MILLISECONDS);
    assertNull(exceptionHolder[0]);
}
 
Example 7
Source File: SessionDao.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
public void close() {
    System.out.println("Closing all sockets...");
    DefaultChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    userSession.forEach((userKey, session) -> {
        allChannels.addAll(session.appChannels);
        allChannels.addAll(session.hardwareChannels);
    });
    allChannels.close().awaitUninterruptibly();
}
 
Example 8
Source File: NettyClient2.java    From wind-im with Apache License 2.0 5 votes vote down vote up
public Future<IRedisCommandResponse> sendRedisCommand(final RedisCommand redisCommand) {
	final Future<IRedisCommandResponse> responseFuture;
	// logger.info("send push message {} {} {}", channelPromise,
	// channelPromise.isSuccess(),
	// channelPromise.channel().isActive());
	if (channelPromise != null) {
		final ChannelPromise readyPromise = this.channelPromise;

		final DefaultPromise<IRedisCommandResponse> responsePromise = new DefaultPromise<IRedisCommandResponse>(
				readyPromise.channel().eventLoop());
		// 提交一个事件
		readyPromise.channel().eventLoop().submit(new Runnable() {
			@Override
			public void run() {
				// 将这个结果赋值给responsePromise
				NettyClient2.this.responsePromise = responsePromise;
			}
		});

		readyPromise.channel().writeAndFlush(redisCommand).addListener(new GenericFutureListener<ChannelFuture>() {
			@Override
			public void operationComplete(final ChannelFuture future) throws Exception {
				if (!future.isSuccess()) {
					// 如果失败了,直接将promise返回
					responsePromise.tryFailure(future.cause());
					logger.error("send push message error: {},cause={}", redisCommand, future.cause());
				} else {
					// logger.info("write data to platform success");
				}
			}
		});
		responseFuture = responsePromise;
	} else {
		logger.error("send push error because client is not connected: {}", redisCommand.toString());
		responseFuture = new FailedFuture<IRedisCommandResponse>(GlobalEventExecutor.INSTANCE, CONNECT_EXCEPTION);
	}
	return responseFuture;
}
 
Example 9
Source File: HttpServer.java    From cantor with Apache License 2.0 5 votes vote down vote up
public HttpServer(@NonNull EventLoopGroup acceptors,
                  @NonNull EventLoopGroup workers,
                  @NonNull HttpServerHandler handler) {
    this.handler = handler;
    this.channelGroup = new DefaultChannelGroup("netserver-channels",
                                                GlobalEventExecutor.INSTANCE);
    this.bootstrap = Bootstraps.serverBootstrap(acceptors, workers);
}
 
Example 10
Source File: EpollSocketChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected Executor closeExecutor() {
    if (config().getSoLinger() > 0) {
        return GlobalEventExecutor.INSTANCE;
    }
    return null;
}
 
Example 11
Source File: ChannelGroupItem.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
public ChannelGroup getGroup() {
    ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    if(!CollectionUtils.isEmpty(items)) {
        items.forEach((itemId, channel) -> channelGroup.add(channel));
    }
    
    return channelGroup;
}
 
Example 12
Source File: LauncherNettyServer.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public LauncherNettyServer(LaunchServer server) {
    LaunchServerConfig.NettyConfig config = server.config.netty;
    NettyObjectFactory.setUsingEpoll(config.performance.usingEpoll);
    if (config.performance.usingEpoll) {
        LogHelper.debug("Netty: Epoll enabled");
    }
    if (config.performance.usingEpoll && !Epoll.isAvailable()) {
        LogHelper.error("Epoll is not available: (netty,perfomance.usingEpoll configured wrongly)", Epoll.unavailabilityCause());
    }
    bossGroup = NettyObjectFactory.newEventLoopGroup(config.performance.bossThread);
    workerGroup = NettyObjectFactory.newEventLoopGroup(config.performance.workerThread);
    serverBootstrap = new ServerBootstrap();
    service = new WebSocketService(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), server);
    serverBootstrap.group(bossGroup, workerGroup)
            .channelFactory(NettyObjectFactory.getServerSocketChannelFactory())
            .handler(new LoggingHandler(config.logLevel))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    NettyConnectContext context = new NettyConnectContext();
                    //p.addLast(new LoggingHandler(LogLevel.INFO));
                    pipeline.addLast("http-codec", new HttpServerCodec());
                    pipeline.addLast("http-codec-compressor", new HttpObjectAggregator(65536));
                    if (server.config.netty.ipForwarding)
                        pipeline.addLast("forward-http", new NettyIpForwardHandler(context));
                    pipeline.addLast("websock-comp", new WebSocketServerCompressionHandler());
                    pipeline.addLast("websock-codec", new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
                    if (server.config.netty.fileServerEnabled)
                        pipeline.addLast("fileserver", new FileServerHandler(server.updatesDir, true, config.showHiddenFiles));
                    pipeline.addLast("launchserver", new WebSocketFrameHandler(context, server, service));
                    pipelineHook.hook(context, ch);
                }
            });
}
 
Example 13
Source File: FSMTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testDenyPeer() {
    this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
            this.speakerListener, new StrictBGPPeerRegistry());
    this.clientSession.channelActive(null);
    assertEquals(1, this.receivedMsgs.size());
    assertTrue(this.receivedMsgs.get(0) instanceof Notify);
}
 
Example 14
Source File: NioDatagramChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Test try to reproduce issue #1335
 */
@Test
public void testBindMultiple() throws Exception {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        for (int i = 0; i < 100; i++) {
            Bootstrap udpBootstrap = new Bootstrap();
            udpBootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
            DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap
                    .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
            channelGroup.add(datagramChannel);
        }
        Assert.assertEquals(100, channelGroup.size());
    } finally {
        channelGroup.close().sync();
        group.shutdownGracefully().sync();
    }
}
 
Example 15
Source File: ServerGroups.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
public final void init() {
    allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    serverGroup = Connector.newEventLoopGroup(2);
    childGroup = Connector.newEventLoopGroup(configManager.getNettyThreads());
    backendGroup = Connector.newEventLoopGroup(configManager.getNettyClientThreads());
}
 
Example 16
Source File: DefaultChannnelGroupTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotThrowBlockingOperationException() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.childHandler(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            allChannels.add(ctx.channel());
        }
    });
    b.channel(NioServerSocketChannel.class);

    ChannelFuture f = b.bind(0).syncUninterruptibly();

    if (f.isSuccess()) {
        allChannels.add(f.channel());
        allChannels.close().awaitUninterruptibly();
    }

    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
    bossGroup.terminationFuture().sync();
    workerGroup.terminationFuture().sync();
}
 
Example 17
Source File: ThreadPerChannelEventLoopGroup.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
    public ChannelFuture register(Channel channel) {
        if (channel == null) {
            throw new NullPointerException("channel");
        }
        try {
//            获取事件组
            EventLoop l = nextChild();
//            注册通道
            return l.register(new DefaultChannelPromise(channel, l));
        } catch (Throwable t) {
            return new FailedChannelFuture(channel, GlobalEventExecutor.INSTANCE, t);
        }
    }
 
Example 18
Source File: ServerGroups.java    From serve with Apache License 2.0 5 votes vote down vote up
public final void init() {
    allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    serverGroup = Connector.newEventLoopGroup(2);
    childGroup = Connector.newEventLoopGroup(configManager.getNettyThreads());
    backendGroup = Connector.newEventLoopGroup(configManager.getNettyClientThreads());
}
 
Example 19
Source File: FSMTest.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() throws UnknownHostException {
    MockitoAnnotations.initMocks(this);
    final List<BgpParameters> tlvs = new ArrayList<>();
    final List<OptionalCapabilities> capas = new ArrayList<>();

    capas.add(new OptionalCapabilitiesBuilder()
        .setCParameters(new CParametersBuilder()
            .addAugmentation(new CParameters1Builder()
                .setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
                    .setAfi(this.ipv4tt.getAfi())
                    .setSafi(this.ipv4tt.getSafi())
                    .build())
                .build())
            .build())
        .build());
    capas.add(new OptionalCapabilitiesBuilder()
        .setCParameters(new CParametersBuilder()
            .addAugmentation(new CParameters1Builder()
                .setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
                    .setAfi(this.linkstatett.getAfi())
                    .setSafi(this.linkstatett.getSafi())
                    .build())
                .build())
            .build())
        .build());
    capas.add(new OptionalCapabilitiesBuilder()
        .setCParameters(new CParametersBuilder()
            .setAs4BytesCapability(new As4BytesCapabilityBuilder()
                .setAsNumber(new AsNumber(Uint32.valueOf(30)))
                .build())
            .build())
        .build());
    capas.add(new OptionalCapabilitiesBuilder()
            .setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
    capas.add(new OptionalCapabilitiesBuilder()
            .setCParameters(new CParametersBuilder()
                .addAugmentation(new CParameters1Builder()
                    .setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build())
                    .build())
                .build())
            .build());


    tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capas).build());
    final BGPSessionPreferences prefs = new BGPSessionPreferences(new AsNumber(Uint32.valueOf(30)), (short) 3,
            new BgpId("1.1.1.1"), new AsNumber(Uint32.valueOf(30)), tlvs);

    final ChannelFuture f = mock(ChannelFuture.class);
    doReturn(null).when(f).addListener(any(GenericFutureListener.class));

    final InetAddress peerAddress = InetAddress.getByName("1.1.1.2");
    doAnswer(invocation -> {
        final Object[] args = invocation.getArguments();
        FSMTest.this.receivedMsgs.add((Notification) args[0]);
        return f;
    }).when(this.speakerListener).writeAndFlush(any(Notification.class));
    doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
    doReturn(null).when(this.eventLoop).schedule(any(Runnable.class), any(long.class),
            any(TimeUnit.class));
    doReturn("TestingChannel").when(this.speakerListener).toString();
    doReturn(new InetSocketAddress(peerAddress, 179)).when(this.speakerListener).remoteAddress();
    doReturn(new InetSocketAddress(peerAddress, 179)).when(this.speakerListener).localAddress();
    doReturn(this.pipeline).when(this.speakerListener).pipeline();
    doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class),
            any(ChannelHandler.class));
    doReturn(null).when(this.pipeline).replace(ArgumentMatchers.<Class<ChannelHandler>>any(), any(String.class),
            any(ChannelHandler.class));
    doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
    doReturn(mock(ChannelFuture.class)).when(this.speakerListener).close();

    final BGPPeerRegistry peerRegistry = new StrictBGPPeerRegistry();
    peerRegistry.addPeer(new IpAddressNoZone(new Ipv4AddressNoZone(peerAddress.getHostAddress())),
            new SimpleSessionListener(), prefs);

    this.clientSession = new BGPClientSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
            this.speakerListener, peerRegistry);

    this.classicOpen = new OpenBuilder()
            .setMyAsNumber(Uint16.valueOf(30))
            .setHoldTimer(Uint16.valueOf(3))
            .setVersion(new ProtocolVersion(Uint8.valueOf(4)))
            .setBgpParameters(tlvs)
            .setBgpIdentifier(new Ipv4AddressNoZone("1.1.1.2"))
            .build();
}
 
Example 20
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 4 votes vote down vote up
HttpServerHandler(Supplier<String> contextPathSupplier, CommonHandler commonHandler) {
    this.contextPathSupplier = contextPathSupplier;
    this.commonHandler = commonHandler;
    allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}