基于nodejs和activeMQ的消息推送

来源:互联网 发布:mysql添加表分区 编辑:程序博客网 时间:2024/05/22 05:34


    博客分类: 
  • NodeJs
  • ActiveMQ
NodeJsSocket.ioStompActiveMQ

       好久没来写博客了,感觉自己堕落了,哈哈,LZ糊里糊涂的又换了家单位,空余时间研究了一下nodejs,顺势搞了这个demo,今天来聊聊基于nodejs和activeMQ的消息推送,内容不算复杂,新手也能一看即会。

       首先介绍下一点背景,为什么搞这个东西,LZ上家公司是做监控项目的,很多告警都要实时推送到web端,以前的技术架构是flex+corba+mq(自己封装的),早期B/S架构的实时推送无非就两种,一个是基于插件的长连接,另外一个就是轮训或者Comet,前者受限于flash技术的衰败肯定会逐渐退出历史舞台,后者的低效率在数据量较大的情况下有随时崩溃的可能。随着html5的web socket技术的产生,很多前端socket技术,例如socket.io逐步得到重用,配合nodejs使用,一个前后端socket连接就可以很轻松地解决问题。

       本篇使用技术socket.io+nodeJs+stomp+activeMQ,具体的技术简介就不贴了,各位可以在网络上轻松找到,这里直接代码开路。首先是页面index.htm

Html代码  收藏代码
  1. <html>  
  2. <head>  
  3.   <style type="text/css">  
  4.     #messages { padding: 0px; list-style-type: none;}  
  5.     #messages li { padding: 2px 0px; border-bottom: 1px solid #ccc; }  
  6.   </style>  
  7.   <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>  
  8.   <script src="/socket.io/socket.io.js"></script>  
  9.   <script>  
  10.       $(function() {  
  11.           var socket = io.connect();  
  12.           socket.on('connect', function() {  
  13.                 //  
  14.           });  
  15.           socket.on('message', function(message) {  
  16.               $('#messages').append($('<li></li>').text(message));  
  17.           });  
  18.           socket.on('disconnect', function() {  
  19.               $('#messages').append('<li>Disconnected</li>');  
  20.           });  
  21.       });  
  22.   </script>  
  23. </head>  
  24. <body>  
  25.  <ul id="messages"></ul>  
  26.  <hr>  
  27. </body>  
  28. </html>  

        代码中的/socket.io/socket.io.js,不是真实存在的,是nodejs加载的socket.io模块,这个插件需要在nodejs中进行添加,命令如下:

Js代码  收藏代码
  1. npm install socket.io  

       接下来是nodejs端代码,运行该代码前,要首先启动activeMQ,保证activeMQ,监听了stomp协议和61613端口,LZ在这方面吃了亏,浪费了好长时间,配置文件目录:apache-activemq-5.8.0\conf\activemq.xml

Xml代码  收藏代码
  1. <transportConnectors>  
  2.         <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->  
  3.         <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireformat.maxFrameSize=104857600"/>  
  4.         <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireformat.maxFrameSize=104857600"/>  
  5.     <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireformat.maxFrameSize=104857600"/>  
  6. </transportConnectors>  

 

Js代码  收藏代码
  1. var Stomp = require('stomp-client');    
  2. var destination = '/topic/myTopic';    
  3. var client = new Stomp('127.0.0.1', 61613, 'user''pass');    
  4.   
  5. var fs = require('fs'),  
  6.     http = require('http'),  
  7.     sio = require('socket.io');  
  8.   
  9. var server = http.createServer(function(req, res) {  
  10.     res.writeHead(200, { 'Content-type''text/html' });  
  11.     res.end(fs.readFileSync('./index.htm'));  
  12. });  
  13. server.listen(8888, function() {  
  14.     console.log('Server listening at http://localhost:8888/');  
  15. });  
  16. // Attach the socket.io server  
  17. io = sio.listen(server);  
  18. var tempSockets = [];  
  19.    
  20. io.sockets.on('connection'function(socket) {  
  21.     console.log('socket connection success!!!');  
  22.     tempSockets.push(socket);  
  23.     socket.on('disconnect',function(){  
  24.     });  
  25. });  
  26.   
  27. client.connect(function(sessionId) {    
  28.     client.subscribe(destination, function(body, headers) {    
  29.         console.log('From MQ:', body);  
  30.         //tempSocket.broadcast.emit('message', body);  
  31.         tempSockets.forEach(function(socket) {  
  32.             if(socket.connected)  
  33.             {  
  34.                 socket.send(body);  
  35.             }  
  36.         })  
  37.     });  
  38.     var i = 0;  
  39.     function publish(){  
  40.         setTimeout(function(){  
  41.             client.publish(destination, 'Hello World!'+(i++));  
  42.             //publish();  
  43.         },1000);  
  44.     }  
  45.     publish();  
  46. });  

       文中的stomp-client模块也需要nodejs添加

Java代码  收藏代码
  1. npm install stomp-client  

        上面代码中,client.publish(destination, 'Hello World!'+(i++)),是nodejs作为提供者向activeMQ发送消息,实际应用中是java端的提供者,代码如下:

Java代码  收藏代码
  1. package com.feng.activemq;  
  2.   
  3. import javax.jms.Connection;  
  4. import javax.jms.Destination;  
  5. import javax.jms.JMSException;  
  6. import javax.jms.MessageProducer;  
  7. import javax.jms.Session;  
  8. import javax.jms.TextMessage;  
  9.   
  10. import org.apache.activemq.ActiveMQConnectionFactory;  
  11.   
  12. /** 
  13.  * @author songfeng 
  14.  * @version 1.0. 
  15.  */  
  16. public class SendMessage  
  17. {  
  18.   
  19.     private static final String url = "tcp://localhost:61616";  
  20.     private static final String QUEUE_NAME = "choice.queue";  
  21.     private static final String TOPIC_NAME = "myTopic";  
  22.     protected String expectedBody = "<hello>world!</hello>";  
  23.   
  24.     public void sendMessage() throws JMSException  
  25.     {  
  26.         Connection connection = null;  
  27.         MessageProducer producer = null;  
  28.         Session session = null;  
  29.         try  
  30.         {  
  31.             ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);  
  32.             connection = (Connection) connectionFactory.createConnection();  
  33.             connection.start();  
  34.             session = (Session) connection.createSession(false,  
  35.                     Session.AUTO_ACKNOWLEDGE);  
  36.             //Destination destination = session.createQueue(QUEUE_NAME);  
  37.             Destination destination = session.createTopic(TOPIC_NAME);  
  38.             producer = session.createProducer(destination);  
  39.             for(int i = 1 ; i <= 20; i++)  
  40.             {  
  41.                 TextMessage message = session.createTextMessage(expectedBody+i);  
  42.                 message.setStringProperty("headname""remoteB");  
  43.                 producer.send(message);  
  44.                 Thread.sleep(1000l);  
  45.             }  
  46.         }  
  47.         catch (Exception e)  
  48.         {  
  49.             e.printStackTrace();  
  50.         }  
  51.         finally   
  52.         {  
  53.             producer.close();  
  54.             session.close();  
  55.             connection.close();  
  56.         }  
  57.     }  
  58.   
  59.     public static void main(String[] args)  
  60.     {  
  61.         SendMessage sendMsg = new SendMessage();  
  62.         try  
  63.         {  
  64.             sendMsg.sendMessage();  
  65.         }  
  66.         catch (Exception ex)  
  67.         {  
  68.             System.out.println(ex.toString());  
  69.         }  
  70.     }  
  71. }  


原创粉丝点击