@Override protected void serviceInit() throws Exception { final SslContext sslCtx; if (config.isSsl()) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } Class clazz; if (config.isUseEpoll()) { group = new EpollEventLoopGroup(config.getChildNioEventThreads()); clazz = EpollSocketChannel.class; } else { group = new NioEventLoopGroup(config.getChildNioEventThreads()); clazz = NioSocketChannel.class; } bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024); bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger()); bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT); bootstrap .group(group) .channel(clazz) .handler( new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), config.getHost(), config.getPort())); } p.addLast( new MsgPackEncoder(), new MsgPackDecoder(config.getPayload()), new ClientHandler(ClientProxy.this)); } }); }
@Override protected void serviceStart() throws Exception { if (bootstrap != null) { ChannelFuture channelFuture = bootstrap.connect(config.getHost(), config.getPort()).sync(); channelFuture.awaitUninterruptibly(config.getConnectTimeout(), TimeUnit.MILLISECONDS); if (channelFuture.isSuccess()) { channel = channelFuture.channel(); if (NetUtils.toAddressString((InetSocketAddress) channel.remoteAddress()) .equals(NetUtils.toAddressString((InetSocketAddress) channel.localAddress()))) { channel.close(); throw new ClientConnectException( "Failed to connect " + config.getHost() + ":" + config.getPort() + ". Cause by: Remote and local address are the same"); } } else { throw new ClientTimeoutException(channelFuture.cause()); } } }
public ClientProxy(Config config, ClassLoader loader) { super("ClientProxy" + ":" + config.getRemoteAddress().toString()); this.config = config; this.loader = loader; }