Search in sources :

Example 61 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project xian by happyyangyuan.

the class RpcNettyClient method lazyInit.

/**
 * @param nodeId The node's id to which you want to initialize the connection. This method is thread-safe because it is synchronized.
 * @throws info.xiancloud.plugin.distribution.exception.ApplicationInstanceOfflineException Because the destination node is offline, of cause you cannot initialize the connection.
 * @throws Exception                                                                        Other unknown exceptions.
 */
private static void lazyInit(String nodeId) throws Exception {
    lock.lock();
    String host = null;
    int port = -1;
    try {
        if (channelAvailable(nodeId)) {
            LOG.debug(String.format("RpcClient:已经存在一个与%s的长连接,不再新建连接.", nodeId));
            return;
        }
        LOG.info(String.format("RpcClient:开始新建与%s的长连接...", nodeId));
        ApplicationInstance node = ApplicationRouter.singleton.getInstance(nodeId);
        // 如果是在同一台主机内部部署的两个节点,那么避免走交换机、路由器了
        host = Objects.equals(node.getAddress(), EnvUtil.getLocalIp()) ? "127.0.0.1" : node.getAddress();
        port = node.getPort();
        final SslContext sslCtx;
        if (SSL) {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }
        EventLoopGroup group = new NioEventLoopGroup(1);
        Bootstrap b = new Bootstrap();
        b.group(group).option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(// 10m
        10 * 1024 * 1024, // 20m
        20 * 1024 * 1024)).channel(NioSocketChannel.class).handler(new RpcNettyClientInitializer(sslCtx, nodeId)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100);
        Channel connectedChannel = b.connect(host, port).sync().channel();
        connectedChannel.closeFuture().addListener(future -> {
            group.shutdownGracefully();
            LOG.info("The EventLoopGroup has been terminated completely and all Channels that belong to the group have been closed.");
        });
        nodeId_to_connectedChannel_map.put(nodeId, connectedChannel);
        LOG.info(new JSONObject() {

            {
                put("toNodeId", nodeId);
                put("rpcRemoteAddress", connectedChannel.remoteAddress().toString());
                put("type", "rpcChannelConnected");
                put("description", String.format("RpcClient:与%s的长连接建立完毕, remoteAddress=%s", nodeId, connectedChannel.remoteAddress()));
            }
        }.toJSONString());
    } catch (Throwable e) {
        throw new Exception(String.format("与远程节点%s建立长连接失败:host=%s,port=%s", nodeId, host, port), e);
    } finally {
        lock.unlock();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ApplicationInstanceOfflineException(info.xiancloud.core.distribution.exception.ApplicationInstanceOfflineException) ApplicationInstance(info.xiancloud.core.distribution.service_discovery.ApplicationInstance) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) JSONObject(com.alibaba.fastjson.JSONObject) Bootstrap(io.netty.bootstrap.Bootstrap) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 62 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project bgpcep by opendaylight.

the class BGPDispatcherImpl method createClient.

@VisibleForTesting
public synchronized Future<BGPSessionImpl> createClient(final InetSocketAddress localAddress, final InetSocketAddress remoteAddress, final int retryTimer, final boolean reuseAddress) {
    final Bootstrap clientBootStrap = createClientBootStrap(KeyMapping.getKeyMapping(), reuseAddress);
    clientBootStrap.localAddress(localAddress);
    return createClient(remoteAddress, retryTimer, clientBootStrap);
}
Also used : Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 63 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project bgpcep by opendaylight.

the class BmpDispatcherImpl method createClient.

@Override
public ChannelFuture createClient(final InetSocketAddress remoteAddress, final BmpSessionListenerFactory slf, final KeyMapping keys) {
    final Bootstrap bootstrap = createClientBootstrap(this.sessionFactory, this.hf, BmpDispatcherUtil::createChannelWithDecoder, slf, remoteAddress, this.workerGroup, CONNECT_TIMEOUT, keys);
    final ChannelFuture channelPromise = bootstrap.connect();
    channelPromise.addListener(new BootstrapListener(bootstrap, remoteAddress, slf, keys));
    LOG.debug("Initiated BMP Client {} at {}.", channelPromise, remoteAddress);
    return channelPromise;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Bootstrap(io.netty.bootstrap.Bootstrap) BmpDispatcherUtil.createServerBootstrap(org.opendaylight.protocol.bmp.impl.BmpDispatcherUtil.createServerBootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BmpDispatcherUtil.createClientBootstrap(org.opendaylight.protocol.bmp.impl.BmpDispatcherUtil.createClientBootstrap)

Example 64 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project bgpcep by opendaylight.

the class BmpDispatcherUtil method createClientBootstrap.

public static Bootstrap createClientBootstrap(@Nonnull final BmpSessionFactory sessionFactory, @Nonnull final BmpHandlerFactory hf, @Nonnull CreateChannel createChannel, @Nonnull final BmpSessionListenerFactory slf, @Nonnull final InetSocketAddress remoteAddress, @Nullable final SocketAddress localAddress, @Nonnull final EventLoopGroup workerGroup, final int connectTimeout, @Nonnull final KeyMapping keys, boolean reuseAddress, boolean tryEpollSocket) {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    bootstrap.group(workerGroup);
    bootstrap.handler(createChannel.create(sessionFactory, hf, slf));
    if (localAddress != null) {
        bootstrap.localAddress(localAddress);
    }
    bootstrap.remoteAddress(remoteAddress);
    if (!tryEpollSocket) {
        bootstrap.channel(NioSocketChannel.class);
    } else {
        if (Epoll.isAvailable()) {
            bootstrap.channel(EpollSocketChannel.class);
        } else {
            bootstrap.channel(NioSocketChannel.class);
        }
        if (!keys.isEmpty()) {
            if (Epoll.isAvailable()) {
                bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys);
            } else {
                throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
            }
        }
    }
    return bootstrap;
}
Also used : Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 65 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project incubator-pulsar by apache.

the class DiscoveryServiceTest method connectToService.

/**
 * creates ClientHandler channel to connect and communicate with server
 *
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PrivateKey(java.security.PrivateKey) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SessionExpiredException(org.apache.zookeeper.KeeperException.SessionExpiredException) ExecutionException(java.util.concurrent.ExecutionException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)429 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)207 Channel (io.netty.channel.Channel)194 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)189 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)169 ChannelFuture (io.netty.channel.ChannelFuture)152 EventLoopGroup (io.netty.channel.EventLoopGroup)139 SocketChannel (io.netty.channel.socket.SocketChannel)123 InetSocketAddress (java.net.InetSocketAddress)119 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)113 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)108 Test (org.junit.jupiter.api.Test)89 ChannelPipeline (io.netty.channel.ChannelPipeline)76 LocalChannel (io.netty.channel.local.LocalChannel)74 LocalServerChannel (io.netty.channel.local.LocalServerChannel)71 LocalAddress (io.netty.channel.local.LocalAddress)66 CountDownLatch (java.util.concurrent.CountDownLatch)62 IOException (java.io.IOException)60 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)56 ChannelInitializer (io.netty.channel.ChannelInitializer)45