基於Netty與RabbitMQ的Message Service

來源:互聯網
上載者:User

標籤:

Netty作為一個高效能的非同步網路開發架構,可以作為各種服務的開發架構。

前段時間的一個項目涉及到硬體裝置即時資料的採集,採用Netty作為採集服務的實現架構,同時使用RabbitMQ作為採集服務和各個其他模組的通訊訊息佇列,整個服務架構圖如下:

1、裝置TCP訊息解析:

NettyMQServer和採集裝置Device之間採用TCP通訊,TCP訊息的訊息的解析可以使用LengthFieldBasedFrameDecoder(訊息頭和訊息體),可以有效解決TCP訊息“粘包”問題。

2、給裝置發訊息:

首先在串連建立時,要保留TCP的串連:

static final ChannelGroup channels = new DefaultChannelGroup(            GlobalEventExecutor.INSTANCE);    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        // A closed channel will be removed from ChannelGroup automatically        channels.add(ctx.channel());    }

當需要給某個裝置發訊息的時候,可以遍曆該ChannelGroup,找到對應的Channel,給該Channel發送訊息:

for (io.netty.channel.Channel c : EchoServerHandler.channels) {                            ByteBuf msg = Unpooled.copiedBuffer(message.getBytes());                            c.writeAndFlush(msg);                        }

3、心跳檢測

當某個裝置Device由於斷電或是其他原因導致裝置不正常無法採集資料,Netty服務端需要知道該裝置是否在正常工作,可以使用Netty的IdleStateHandler,範例程式碼如下:

ch.pipeline().addLast(new IdleStateHandler(3*60,0,0));ch.pipeline().addLast(new HeartBeatHandler());/** * Handler implementation for heart beating. */public class HeartBeatHandler extends ChannelInboundHandlerAdapter{    @Override    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)            throws Exception {        if (evt instanceof IdleStateEvent) {            IdleStateEvent event = (IdleStateEvent) evt;            if (event.state() == IdleState.READER_IDLE) {                // Read timeout                System.out.println("READER_IDLE: read timeout from "+ctx.channel().remoteAddress());                //ctx.disconnect(); //Channel disconnect            }        }    }}

4、RabbitMQ訊息接收與發送

NettyMQServer訊息發送採用了Spring AMQP,只需要在設定檔中簡單配置一下,就可以方便使用。

NettyMQServer訊息接收同樣可以採用Spring AMQP,但由於對Spring相關的配置不是很熟悉,為了更好的使用MQ,這裡使用了RabbitMQ Client Java API來實現:

                    Connection connection = connnectionFactory.newConnection();                    Channel channel = connection.createChannel();                    channel.exchangeDeclare(exchangeName, "direct", true,                            false, null);                    channel.queueDeclare(queueName, true, false, false, null);                    channel.queueBind(queueName, exchangeName, routeKey);                    // process the message one by one                    channel.basicQos(1);                    QueueingConsumer queueingConsumer = new QueueingConsumer(                            channel);                    // auto-ack is false                    channel.basicConsume(queueName, false, queueingConsumer);                    while (true) {                        QueueingConsumer.Delivery delivery = queueingConsumer                                .nextDelivery();                        String message = new String(delivery.getBody());                        log.debug("Mq Receiver get message");                        // Send the message to all connected clients                        // If you want to send to a specified client, just add                        // your own logic and ack manually                        // Be aware that ChannelGroup is thread safe                        log.info(String.format("Conneted client number: %d",                                EchoServerHandler.channels.size()));                        for (io.netty.channel.Channel c : EchoServerHandler.channels) {                            ByteBuf msg = Unpooled.copiedBuffer(message                                    .getBytes());                            c.writeAndFlush(msg);                        }                        // manually ack to MQ server the message is consumed.                        channel.basicAck(delivery.getEnvelope()                                .getDeliveryTag(), false);

RabbitMQ的使用方式:http://www.cnblogs.com/luxiaoxun/p/3918054.html

 

原始碼:https://github.com/luxiaoxun/NettyMqServer

 

參考:

http://netty.io/

http://netty.io/4.0/api/io/netty/handler/codec/LengthFieldBasedFrameDecoder.html

http://netty.io/4.0/api/io/netty/handler/timeout/IdleStateHandler.html

 

基於Netty與RabbitMQ的Message Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.