use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project BRFS by zhangnianli.
the class AsyncTcpClientGroup method createClient.
@Override
public TcpClient<BaseMessage, BaseResponse> createClient(TcpClientConfig config, Executor executor) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator());
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutMillis());
if (executor == null) {
executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
}
AsyncTcpClient client = new AsyncTcpClient(executor);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new IdleStateHandler(0, DEFAULT_WRITE_IDLE_TIMEOUT_SECONDS, 0)).addLast(new BaseMessageEncoder()).addLast(new BaseResponseDecoder()).addLast(new SimpleChannelInboundHandler<TokenMessage<BaseResponse>>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TokenMessage<BaseResponse> msg) throws Exception {
client.handle(msg.messageToken(), msg.message());
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.WRITER_IDLE) {
ctx.writeAndFlush(new BaseMessage(-1));
}
}
}
});
}
});
ChannelFuture future = bootstrap.connect(config.remoteAddress()).sync();
if (!future.isSuccess()) {
return null;
}
Channel channel = future.channel();
channelList.add(channel);
channel.closeFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
channelList.remove(channel);
}
});
LOG.info("create tcp client for {}", config.remoteAddress());
client.attach(channel);
return client;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project riposte by Nike-Inc.
the class ComponentTestUtils method executeRequest.
public static Pair<Integer, String> executeRequest(HttpRequest request, int port, int incompleteCallTimeoutMillis) throws Exception {
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
CompletableFuture<Pair<Integer, String>> responseFromServer = new CompletableFuture<>();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof FullHttpResponse) {
// Store the proxyServer response for asserting on later.
FullHttpResponse responseMsg = (FullHttpResponse) msg;
responseFromServer.complete(Pair.of(responseMsg.getStatus().code(), responseMsg.content().toString(UTF_8)));
} else {
// Should never happen.
throw new RuntimeException("Received unexpected message type: " + msg.getClass());
}
}
});
}
});
// Connect to the proxyServer.
Channel ch = bootstrap.connect("localhost", port).sync().channel();
// Send the request.
ch.writeAndFlush(request);
// Wait for the response to be received
try {
responseFromServer.get(incompleteCallTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
} finally {
ch.close();
}
// If we reach here then the call should be complete.
return responseFromServer.get();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project activemq-artemis by apache.
the class NettyConnectorWithHTTPUpgradeTest method startWebServer.
private void startWebServer(int port) throws Exception {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
final SSLContext context;
if (useSSL) {
context = SSLSupport.createContext("JKS", SERVER_SIDE_KEYSTORE, PASSWORD, null, null, null);
} else {
context = null;
}
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// create a HTTP server
ChannelPipeline p = ch.pipeline();
if (useSSL) {
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
SslHandler handler = new SslHandler(engine);
p.addLast("ssl", handler);
}
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("encoder", new HttpResponseEncoder());
p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
// handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting.
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
for (Map.Entry<String, String> entry : request.headers()) {
System.out.println(entry);
}
String upgrade = request.headers().get(UPGRADE);
String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
response.headers().set(UPGRADE, upgrade);
response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey));
ctx.writeAndFlush(response);
// when the handshake is successful, the HTTP handlers are removed
ctx.pipeline().remove("decoder");
ctx.pipeline().remove("encoder");
ctx.pipeline().remove(this);
System.out.println("HTTP handshake sent, transferring channel");
// transfer the control of the channel to the Netty Acceptor
NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName);
acceptor.transfer(ctx.channel());
// at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
}
}
});
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
});
b.bind(port).sync();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project alibaba-mom by younfor.
the class DefaultConsumer method prepare.
@Override
public void prepare() {
SIP = System.getProperty("SIP");
if (SIP == null)
SIP = "127.0.0.1";
System.out.println("consumer connect:" + System.getProperty("SIP"));
group = new NioEventLoopGroup();
try {
bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new RpcEncoder()).addLast(new RpcDecoder()).addLast(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
connect();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
logger.error("消费者异常关闭:");
e.printStackTrace();
ctx.close();
}
@Override
protected void channelRead0(final ChannelHandlerContext ctx, Object info) throws Exception {
logger.debug("client receive msg");
Message msg = (Message) info;
// 返回ACK
final ConsumeResult consumeResult = listener.onMessage(msg);
// 设置谁的 ack
consumeResult.setMsgId(msg.getMsgId());
/*
*设置 consumeResult来源
*/
consumeResult.setGroupId(groupId);
consumeResult.setTopicAndFilter(new TopicAndFilter(topic, filterMap));
// if(Math.random()>0.95){
// new Thread(new Runnable(){
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// try {
// Thread.sleep(10000);
//
// ctx.writeAndFlush(consumeResult);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// }).start();;
// }else
ctx.writeAndFlush(consumeResult);
}
});
}
});
connect();
} catch (InterruptedException e) {
logger.error("消费者抛出异常 " + e.getMessage());
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project alibaba-mom by younfor.
the class DefaultProducer method start.
@Override
public void start() {
SIP = System.getProperty("SIP");
if (SIP == null)
SIP = "127.0.0.1";
System.out.println("connect:" + System.getProperty("SIP"));
group = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new RpcEncoder()).addLast(new LineBasedFrameDecoder(1024 * 256)).addLast(new StringDecoder()).addLast(new SimpleChannelInboundHandler<Object>() {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.error("producer失去broker链接");
connect();
}
@Override
protected void channelRead0(ChannelHandlerContext arg0, Object info) throws Exception {
logger.debug("recv ack: " + (String) info);
if (info != null) /*&&info.toString().startsWith("ackGroup"*/
{
String[] id = ((String) info).split("@");
// System.out.println(id.length+":len:"+id[0]+" | "+id[1]);
if (id[0].startsWith("fail")) {
// System.out.println("无人订阅");
SendResult sr = new SendResult();
sr.setMsgId(id[1]);
resultMap.get(id[1]).put(sr);
} else {
for (int i = 1; i < id.length; i++) {
// System.out.println(id[i]);
SendResult sr = new SendResult();
sr.setMsgId(id[i]);
resultMap.get(id[i]).put(sr);
}
}
// synchronized(lock){
// lock.notifyAll();
// }
} else {
// 异步方式接受数据
if (asyncResults.containsKey((String) info)) {
SendResult sr = new SendResult();
sr.setMsgId((String) info);
asyncResults.get((String) info).onResult(sr);
;
} else {
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("--生产者的异常关闭--" + cause.getMessage());
cause.printStackTrace();
logger.error("重新连接");
ctx.close();
connect();
}
});
}
});
connect();
}
Aggregations