利用stomp.js实现websocket功能,接收ActiveMQ消息队列

一、ActiveMQ消息发送端

package lixj;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MQProducer {

    private static final String USERNAME = "user"; //用户名 
    private static final String PASSWORD = "321";  //密码 
    private static final String BROKENURL = "tcp://192.168.204.31:61616";  
    private static final String Q_NAME = "MessageQueue";  //消息队列
    
    public static void main(String[] args) {
            ConnectionFactory connectionFactory;
            Connection connection;
            Session session;
            Destination destination;
            MessageProducer producer;
            connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKENURL);
            try {
                connection = connectionFactory.createConnection();
                connection.start();
                session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
                destination = session.createQueue(Q_NAME);
                producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                for(int i=0;i<1;i++){
                    //发送消息
                    producer.send(session.createTextMessage("【"+i+"】MQTT测试你有一份收文《测试标题》需要及时处理!+"+new Date()));
                }
                producer.close(); 
                System.out.println("消息发送完毕");
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}

二、web 页面消息接收代码

    <script type="text/javascript" src="/js/stomp.js"></script>
    <script type="text/javascript">
    var url = "ws://192.168.204.31:61614/stomp"; 
    var destination = "MessageQueue";
    var client = Stomp.client(url);
    
    var callbackMSG = function(message) {
        if (message.body) {
            alert("got message with body " + message.body)
        } else {
            alert("got empty message");
        }
    };
    
    var connect_callback = function(frame) {
      client.subscribe(destination, callbackMSG);
    };

    var error_callback = function(error) {
        alert(error.headers.message);
    };
    var headers = {
        login: 'user',
        passcode: '321',
        // additional header
        'client-id': 'my-client-id'
    };
    client.connect(headers, connect_callback, error_callback);
   </script>

 

posted @ 2018-05-24 10:47  李小加  阅读(10110)  评论(1编辑  收藏  举报