ActiveMQ利用ajax收发消息

准备工作:

后台需要导包:

activemq-all.jar

activemq-web.jar

jetty-all.jar

 

 

如果是maven项目:

pom.xml

<dependency>  
    <groupId>org.apache.activemq</groupId>  
    <artifactId>activemq-all</artifactId>  
    <version>5.8.0</version>  
</dependency>  
<dependency>  
    <groupId>org.apache.activemq</groupId>  
    <artifactId>activemq-web</artifactId>  
    <version>5.8.0</version>  
</dependency>  

修改配置:

web.xml配置,主要是配置接收客户端请求的servlet

 

<context-param>

<param-name>org.apache.activemq.brokerURL</param-name>

<param-value>tcp://localhost:61616</param-value>

<description>连接到消息中间件的URL</description>

</context-param>

<servlet>

<servlet-name>AjaxServlet</servlet-name>

<servlet-class>org.apache.activemq.web.AjaxServlet</servlet-class>

<load-on-startup>1</load-on-startup>

<async-supported>true</async-supported>

</servlet>

<servlet-mapping>

<servlet-name>AjaxServlet</servlet-name>

<url-pattern>/amq/*</url-pattern>

</servlet-mapping>

 

说明:

<url-pattern>/amq/*</url-pattern>,配置会在amq.js发送消息时请求的servlet的rul,在amq.js初始化时要做响应的配置.

<load-on-startup>1</load-on-startup>表示这个servlet在tomcat启动时就实例化

<async-supported>true</async-supported>

 

servlet3.0新增异步处理支持<async-supported>true</async-supported>有时候会报

java.lang.IllegalStateException: A filter or servlet of the current chain does not support asynchronous operations. 错误,

解决方法: 再所有的servlet和filter中都声明asyncSupported=true。

 

 

 

js的引用:

1.需要引入3个js  需要在网站下

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>  
<script type="text/javascript" src="js/amq_jquery_adapter.js"></script>  
<script type="text/javascript" src="js/amq.js"></script>

 

2.amq.js需要初始化

<script type="text/javascript">  
   $(document).ready(  
    function()  
    {  
      org.activemq.Amq.init(  
       {   
         uri: 'amq',   
         logging: true,   
         timeout: 1,   
         clientId:(new Date()).getTime().toString()   
       }  
      );  
    });  
   </script>  

 

$(function(){

//mq初始化

var amq = org.activemq.Amq;

var myDestination='topic://test.topic';//test.topic为topic的名称

amq.init({

uri: 'amq', //AjaxServlet所配置对应的URL

logging: true,//激活日志记录

timeout: 20,//保持连接时长,单位为秒

clientId:(new Date()).getTime().toString() //防止多个浏览器窗口标签共享同一个JSESSIONID

});

//发送消息

$("#sendBtn").click(function(){

var msg=$("#msg").val();

var name=$("#name").val();

amq.sendMessage(myDestination, "<message name='"+name+"' msg='"+msg+"'/>");

$("#msg").val("");

});

//接收消息

rcvMessage: function(message){

$("#mqNum").text(message.data);

// $("#distext").append(message.getAttribute('name')+":"+message.getAttribute('msg')+"\n");

console.log(list);



}

};

//注册消息处理器

amq.addListener('handler',myDestination,myHandler.rcvMessage);

});

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-11-28 14:24  诸葛小朙  阅读(1034)  评论(0编辑  收藏  举报