use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project alibaba-mom by younfor.
the class Broker method bind.
/**
* 启动broker之前的netty服务器处理
* @param port
* @throws Exception
*/
public void bind(int port) throws Exception {
// 启动消费进度定时任务
// storeSubscribe(true, 5000);
// scanSendInfotMap();
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 3);
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_BACKLOG, 1024 * 1024).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new RpcDecoder()).addLast(new RpcEncoder()).addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object info) throws Exception {
if (InfoBodyConsumer.class.isInstance(info)) {
// 接受消费者订阅处理
processConsumer((InfoBodyConsumer) info, ctx);
} else if (ConsumeResult.class.isInstance(info)) {
// 收到消费者ConsumeResult
logger.debug(" 收到消费者ConsumeResult");
ConsumerGroup.confirmConsumer((ConsumeResult) info, ctx);
// confirmConsumer((ConsumeResult) info, ctx);
} else if (MessageSend.class.isInstance(info)) {
// System.out.println("收到消息");
MessageManager.recieveMsg((MessageSend) info, ctx);
// MessageManager.recieveMsg((LinkedBlockingQueue)info,ctx);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.error("broker 异常:");
// logger.error(cause.getMessage());
cause.printStackTrace();
ctx.close();
}
});
}
});
//
ChannelFuture future = serverBootstrap.bind(port).sync();
logger.debug("mom服务启动成功...... 绑定端口" + port);
// 等待服务端监听端口关闭
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("smom服务抛出异常 " + e.getMessage());
} finally {
// 优雅退出 释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
logger.debug("mom服务优雅的释放了线程资源...");
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project modules-extra by CubeEngine.
the class HttpRequestHandler method channelRead0.
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception {
InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
this.log.info("{} connected...", inetSocketAddress.getAddress().getHostAddress());
if (!this.server.isAddressAccepted(inetSocketAddress.getAddress())) {
this.log.info("Access denied!");
ctx.channel().close();
}
if (message.getDecoderResult().isFailure()) {
this.error(ctx, RequestStatus.UNKNOWN_ERROR);
this.log.info(message.getDecoderResult().cause(), "The decoder failed on this request...");
return;
}
boolean authorized = this.server.isAuthorized(inetSocketAddress.getAddress());
QueryStringDecoder qsDecoder = new QueryStringDecoder(message.getUri(), this.UTF8, true, 100);
final Parameters params = new Parameters(qsDecoder.parameters(), cm.getProviders());
User authUser = null;
if (!authorized) {
String user = params.get("user", String.class);
String pass = params.get("pass", String.class);
if (user == null || pass == null) {
this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
return;
}
Optional<User> byName = Sponge.getServiceManager().provide(UserStorageService.class).get().get(user);
if (!byName.isPresent()) {
this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
return;
}
UUID id = byName.get().getUniqueId();
// TODO make properly async
CompletableFuture<Boolean> cf = am.isPasswordSet(id).thenCompose(isSet -> am.checkPassword(id, pass).thenApply(correctPassword -> !isSet || !correctPassword));
Boolean authFailed = cf.get();
if (authFailed) {
this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Could not complete authentication", 200));
return;
}
authUser = byName.get();
}
String path = qsDecoder.path().trim();
if (path.length() == 0 || "/".equals(path)) {
this.error(ctx, RequestStatus.ROUTE_NOT_FOUND);
return;
}
path = normalizePath(path);
// is this request intended to initialize a websockets connection?
if (WEBSOCKET_ROUTE.equals(path)) {
WebSocketRequestHandler handler;
if (!(ctx.pipeline().last() instanceof WebSocketRequestHandler)) {
handler = new WebSocketRequestHandler(cm, server, objectMapper, authUser);
ctx.pipeline().addLast("wsEncoder", new TextWebSocketFrameEncoder(objectMapper));
ctx.pipeline().addLast("handler", handler);
} else {
handler = (WebSocketRequestHandler) ctx.pipeline().last();
}
this.log.info("received a websocket request...");
handler.doHandshake(ctx, message);
return;
}
this.handleHttpRequest(ctx, message, path, params, authUser);
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project modules-extra by CubeEngine.
the class WebSocketRequestHandler method doHandshake.
public void doHandshake(ChannelHandlerContext ctx, FullHttpRequest message) {
WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory("ws://" + message.headers().get(HOST) + "/" + WEBSOCKET_ROUTE, null, false);
this.handshaker = handshakerFactory.newHandshaker(message);
if (handshaker == null) {
this.log.info("client is incompatible!");
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
return;
}
this.log.debug("handshaking now...");
this.handshaker.handshake(ctx.channel(), message).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
log.debug("Success!");
} else {
log.debug("Failed!");
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project xian by happyyangyuan.
the class RpcServerDefaultHandler method processMsg.
private void processMsg(final ChannelHandlerContext ctx, final JSONObject json) {
try {
IdManager.makeSureMsgId(json);
if (MessageType.isDefaultRequest(json)) {
UnitRequest request = json.toJavaObject(UnitRequest.class);
request.getContext().setFromRemote(true);
String group = request.getContext().getGroup(), unit = request.getContext().getUnit();
final Consumer<String> backPayloadConsumerOnFailure = payload -> {
LOG.info("rpc server --> client发送失败了,因此这里复用当前长连接响应消息");
ctx.writeAndFlush(payload + Constant.RPC_DELIMITER);
};
ISequencer.build(group, unit, json).sequence(// call this sender if sequencer is succeeded.
new DefaultLocalAsyncSender(request, new NotifyHandler() {
protected void handle(UnitResponse unitResponse) {
LocalNodeManager.sendBack(unitResponse, backPayloadConsumerOnFailure);
}
}), /*failed directly, call this handler*/
new NotifyHandler() {
protected void handle(UnitResponse failureOut) {
LocalNodeManager.sendBack(failureOut, backPayloadConsumerOnFailure);
}
});
} else if (MessageType.isDefaultResponse(json)) {
LOG.debug("这是非常重要的说明:" + "1、客户端发给外部节点的请求期待的响应内容,服务端节在准备好响应结果后立刻与请求端新建一个rpc长连接/复用已存在的长连接,将响应写回去;" + "2、停服务时本地server会先停止,server停止就会关闭socket和server的io线程池,由于server的io线程池和业务线程池是分离的," + "业务线程池会继续运行直到所有任务处理完毕为止。此时,本节点不再有能力接收外部请求了,但是:" + "a.在即将停止的节点内,业务线程池任然需要向外部发送请求以完成业务操作,以及得到响应结果,因此client必须保持打开的。" + "b.在即将停止的节点内,业务线程池需要将本地执行结果返回给远程,这时候server已停,无法复用原管道将结果写回去,因此必须使用依然存活的client" + "将结果写回。" + "因此,有如下逻辑:所有server优先复用当前管道将响应写回去,当SERVER关闭后,业务线程池中后续任务通过未停止的client回写响应结果。");
UnitResponse response = json.toJavaObject(UnitResponse.class);
String ssid = response.getContext().getSsid();
ThreadPoolManager.execute(() -> {
NotifyHandler callback = LocalNodeManager.handleMap.getIfPresent(ssid);
if (callback != null) {
LocalNodeManager.handleMap.invalidate(ssid);
callback.callback(UnitResponse.create(json));
} else {
LOG.error(String.format("ssid=%s的消息没有找到对应的notifyHandler!整个消息内容=%s,", ssid, json), new Throwable());
}
}, response.getContext().getMsgId());
} else
LOG.error("rpc server端只支持request和response两种消息类型,不支持:" + MessageType.getMessageType(json), new RuntimeException());
} catch (Throwable e) {
LOG.error(e);
} finally {
MsgIdHolder.clear();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project rocketmq by apache.
the class RequestHeader method createRemotingServer.
public static RemotingServer createRemotingServer() throws InterruptedException {
NettyServerConfig config = new NettyServerConfig();
RemotingServer remotingServer = new NettyRemotingServer(config);
remotingServer.registerProcessor(0, new NettyRequestProcessor() {
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
request.setRemark("Hi " + ctx.channel().remoteAddress());
return request;
}
@Override
public boolean rejectRequest() {
return false;
}
}, Executors.newCachedThreadPool());
remotingServer.start();
return remotingServer;
}
Aggregations