搭建activemq环境

1. 新建maven项目      spring_activemq_maven

2.导入相关的pom依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xuzhiwen</groupId>
    <artifactId>SSA</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SSA Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <springframework>3.2.5.RELEASE</springframework>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${springframework}</version>
        </dependency>


        <!-- xbean -->

        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean-spring</artifactId>
            <version>3.16</version>
        </dependency>

        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- activemq -->

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.14.3</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SSA</finalName>
    </build>
</project>

3.配置web.xml

 

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!--spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springCore.xml</param-value>
    </context-param>

    <!--spring监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--spring servlet-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>

</web-app>

4.配置:springCore.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.org/schema/data/jpa 
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
        
    <import resource="activemq/mq.xml" />
</beans> 

 

5.配置:springMvc.xml  文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.org/schema/data/jpa 
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
    <!--自动扫描的包-->    
    <context:component-scan base-package="com.xuzhiwen.controller" />
    
    <!--mvc注解-->
    <mvc:annotation-driven />
     
       <!--视图解析器--> 
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
    </bean>
</beans> 

 

6. 配置 :mq.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:amq="http://activemq.apache.org/schema/core"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core-5.12.1.xsd"
        >
    
    <!--jms服务工厂-->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
         <property name="brokerURL" value="tcp://localhost:61616"/>
    </bean>  
    
    <!--连接池-->
    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">  
            <property name="connectionFactory" ref="targetConnectionFactory"/>  
            <property name="maxConnections" value="10"/>  
    </bean>
    
    <!--spring工厂-->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
            <property name="targetConnectionFactory" ref="pooledConnectionFactory"/>  
    </bean> 
    
    <!--配置jmsTemplate(queue)-->
    <bean id="jmsTemplateQ" class="org.springframework.jms.core.JmsTemplate">  
        <property name="connectionFactory" ref="connectionFactory"/>  
        <property name="pubSubDomain" value="false"></property>
    </bean> 
    <!--配置jmsTemplate(queue)-->
    <bean id="jmsTemplateT" class="org.springframework.jms.core.JmsTemplate">  
        <property name="connectionFactory" ref="connectionFactory"/>  
        <property name="pubSubDomain" value="true"></property>
    </bean>
    
    <!-- queue消息监听器 -->  
    <bean id="queueMessageListener1" class="com.xuzhiwen.listener.QueueMessageListener1"/>   
    <bean id="queueMessageListener2" class="com.xuzhiwen.listener.QueueMessageListener2"/>   
    
    <!-- topic消息监听器 -->  
    <bean id="topicMessageListener1" class="com.xuzhiwen.listener.TopicMessageListener1"/> 
    <bean id="topicMessageListener2" class="com.xuzhiwen.listener.TopicMessageListener2"/> 
    
    <!--queue监听容器-->
    <jms:listener-container destination-type="queue" container-type="default" connection-factory="connectionFactory" acknowledge="auto" concurrency="1">
        <jms:listener destination="xzw.queue" ref="queueMessageListener1" />
        <jms:listener destination="xzw.queue" ref="queueMessageListener2" />
    </jms:listener-container>

    <!--topic监听容器-->
    <jms:listener-container destination-type="topic" container-type="default" connection-factory="connectionFactory" acknowledge="auto" concurrency="1">
        <jms:listener destination="xzw.topic" ref="topicMessageListener1" />
        <jms:listener destination="xzw.topic" ref="topicMessageListener2" />
    </jms:listener-container>
    
</beans> 

 

7. 新建消息监听器:

  QueueMessageListener1.java

package com.xuzhiwen.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * @author Administrator
 * queue监听器
 */
public class QueueMessageListener1 implements MessageListener{

    @Override
    public void onMessage(Message msg) {
        try {
            TextMessage message = (TextMessage) msg;
            System.out.println("【queue1】监听到的消息为:----"+message.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

  QueueMessageListener2.java

package com.xuzhiwen.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * @author Administrator
 * queue监听器
 */
public class QueueMessageListener2 implements MessageListener{

    @Override
    public void onMessage(Message msg) {
        try {
            TextMessage message = (TextMessage) msg;
            System.out.println("【queue2】监听到的消息为:----"+message.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

  TopicMessageListener1.java

package com.xuzhiwen.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


/**
 * @author Administrator
 *    topic监听器
 */
public class TopicMessageListener1 implements MessageListener{

    @Override
    public void onMessage(Message msg) {
    try {
            TextMessage message = (TextMessage) msg;
            System.out.println("【topic1】监听到的消息为:----"+message.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

  TopicMessageListener2.java

package com.xuzhiwen.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;


/**
 * @author Administrator
 *    topic监听器
 */
public class TopicMessageListener2 implements MessageListener{

    @Override
    public void onMessage(Message msg) {
    try {
            TextMessage message = (TextMessage) msg;
            System.out.println("【topic2】监听到的消息为:----"+message.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

8. 新建 mvc controllor 

  SendMsgController.java

package com.xuzhiwen.controller;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SendMsgController {
    
    @Autowired
    private JmsTemplate jmsTemplateQ;
    
    @Autowired
    private JmsTemplate jmsTemplateT;
    
    /**
     * 发送到queue
     * @return
     */
    @RequestMapping(value="/sendQueue")
    public String sendQueue(Model model,HttpServletRequest request,HttpServletResponse response){
        final String msg = request.getParameter("message");
        System.out.println(jmsTemplateQ);
        
        jmsTemplateQ.send("xzw.queue", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
        return "send";
    }
        
    /**
     * 发送到topic
     * @return
     */
    @RequestMapping(value="/sendTopic")
    public String sendTopic(Model model,HttpServletRequest request,HttpServletResponse response){
        final String msg = request.getParameter("message");
        System.out.println(jmsTemplateT);
        jmsTemplateT.send("xzw.topic", new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
        return "send";
    }
}

9. 新建发送消息的页面:send.html , send.js 

 

send.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../js/send.js"></script>
</head>
<body>
    <table>
        <tr>
            <td><textarea id="msgQ" rows="8" cols="40"></textarea><button id="sendQueue">queue发送</button></td>
            <td><textarea id="msgT" rows="8" cols="40"></textarea><button id="sendTopic">topic发送</button></td>
        </tr>
    </table>
</body>
</html>

send.js

$(function() {

    /**
     * queue发送
     */
    $("#sendQueue").click(function() {
        var msg = $("#msgQ").val();
        $.ajax({
            url : '../sendQueue',
            type : 'post',
            async : true, // 是否异步
            data : {
                message : msg
            },
            timeout : 5000, // 超时时间
            dataType : 'json', // 返回的数据格式:json/xml/html/script/jsonp/text
            beforeSend : function(xhr) {
                console.log(xhr)
                console.log('发送前')
            },
            success : function(data, textStatus, jqXHR) {
                console.log(data)
                console.log(textStatus)
                console.log(jqXHR)
            },
            error : function(xhr, textStatus) {
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete : function() {
                console.log('结束')
            }
        });
    });

    /**
     * topic发送
     */
    $("#sendTopic").click(function() {
        debugger
        var msg = $("#msgT").val();
        $.ajax({
            url : '../sendTopic',
            type : 'post',
            async : true, // 是否异步
            data : {
                message : msg
            },
            timeout : 5000, // 超时时间
            dataType : 'json', // 返回的数据格式:json/xml/html/script/jsonp/text
            beforeSend : function(xhr) {
                console.log(xhr)
                console.log('发送前')
            },
            success : function(data, textStatus, jqXHR) {
                console.log(data)
                console.log(textStatus)
                console.log(jqXHR)
            },
            error : function(xhr, textStatus) {
                console.log('错误')
                console.log(xhr)
                console.log(textStatus)
            },
            complete : function() {
                console.log('结束')
            }
        });
    });
});

 

10. 启动 运行后,效果如下:

11. 一对一,一对多的区别

queue发送后,结果如下:

topic发送后,结果如下:

 

posted @ 2018-03-02 12:33  beibidewomen  阅读(116)  评论(0编辑  收藏  举报