Search in sources :

Example 1 with RpcEncoder

use of com.alibaba.middleware.race.mom.serializer.RpcEncoder 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服务优雅的释放了线程资源...");
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RpcDecoder(com.alibaba.middleware.race.mom.serializer.RpcDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 2 with RpcEncoder

use of com.alibaba.middleware.race.mom.serializer.RpcEncoder 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());
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) TopicAndFilter(com.alibaba.middleware.race.mom.util.TopicAndFilter) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RpcDecoder(com.alibaba.middleware.race.mom.serializer.RpcDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 3 with RpcEncoder

use of com.alibaba.middleware.race.mom.serializer.RpcEncoder 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();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

RpcEncoder (com.alibaba.middleware.race.mom.serializer.RpcEncoder)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 RpcDecoder (com.alibaba.middleware.race.mom.serializer.RpcDecoder)2 Bootstrap (io.netty.bootstrap.Bootstrap)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2 TopicAndFilter (com.alibaba.middleware.race.mom.util.TopicAndFilter)1 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)1 Channel (io.netty.channel.Channel)1 ChannelFuture (io.netty.channel.ChannelFuture)1 EventLoopGroup (io.netty.channel.EventLoopGroup)1 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)1 LineBasedFrameDecoder (io.netty.handler.codec.LineBasedFrameDecoder)1 StringDecoder (io.netty.handler.codec.string.StringDecoder)1