码迷,mamicode.com
首页 > 其他好文 > 详细

ssm整合ActiveMQ

时间:2017-11-21 01:14:18      阅读:983      评论:0      收藏:0      [点我收藏+]

标签:就会   roc   res   intro   out   app   send   .post   项目   

环境:windows7

本次使用spring+springmvc+mybatis整合activemq

整合结果,项目能正常运行。并且使用postman进行接口测试,没有进行数据的持久化到数据库。

以下是整合内容

===============================================================================

1,pom.xml文件下载activemq的jar包配置,仅贴出activemq的配置

        <!--activemq  -->
        <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-core</artifactId>
      <version>5.7.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-pool</artifactId>
      <version>5.12.2</version>
    </dependency>

        <!-- xbean 如<amq:connectionFactory /> 此次配置主要是因为配置文件中可能读取不到amq标签 -->
    <dependency>
      <groupId>org.apache.xbean</groupId>
      <artifactId>xbean-spring</artifactId>
      <version>4.5</version>
    </dependency>

============================================================================

2,spring的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />


<mvc:default-servlet-handler />
<mvc:annotation-driven /><!-- 必须添加mvc:annotation-driven 否则所有controller失效 -->
<!-- 扫描注解Bean -->
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.jjmc.client.controller" />
<context:component-scan base-package="com.jjmc.client.service" />
<context:component-scan base-package="com.jjmc.client.service.impl" />
<!--     指定Sping组件扫描的基本包路径
    <context:component-scan base-package="com.jjmc.client" >
        这里只扫描Controller,不可重复加载Service
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan> -->
<!--开启这个配置,spring才能识别@Scheduled注解-->  
    <task:annotation-driven/> 
    
    
</beans>

=====================================================================================

3,activemq的配置文件

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core-5.12.2.xsd"



    <amq:connectionFactory id="amqConnectionFactory"
                           brokerURL="tcp://127.0.0.1:61616"
                           userName="admin"
                           password="admin" />


    <!-- 消息传输监听器 处理网络及服务器异常 -->
<!--     <property name="transportListener">
        <bean class="cn.mayongfa.activemq.ActiveMQTransportListener" />
    </property> -->


    <!-- 配置JMS连接工长 -->
    <bean id="connectionFactory"
          class="org.springframework.jms.connection.CachingConnectionFactory">
        <constructor-arg ref="amqConnectionFactory" />
        <property name="sessionCacheSize" value="100" />
    </bean>


    <!-- 定义消息队列(Queue) -->
    <bean id="demoQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- 设置消息队列的名字 -->
        <constructor-arg>
            <value>ActiveMQ</value>
        </constructor-arg>
    </bean>


    <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="demoQueueDestination" />
        <!--JmsTemplate的接收是阻塞式的接收,默认会一直阻塞等待,直到接收到了消息。也可以设置一个最长的等待时间参数,超过这个时间,接收的方法将得到null的结果。  -->
        <property name="receiveTimeout" value="10000" />
        <!-- true是topic,false是queue,默认是false,此处显示写出false。非pub/sub模型(发布/订阅),即队列模式 -->
        <property name="pubSubDomain" value="false" />
        <!-- deliveryMode, priority, timeToLive 的开关,要生效,必须配置为true,默认false-->  
        <property name="explicitQosEnabled" value="true" /> 
        <!-- 发送模式  DeliveryMode.NON_PERSISTENT=1:非持久 ; DeliveryMode.PERSISTENT=2:持久-->
        <property name="deliveryMode" value="1" />
        <!--在发送时,可以设置消息的存活时间,默认为永久有效。  -->
        <!-- <property name="timeToLive" value="5000" /> --><!--此项配置有问题  -->
    <!-- 消息应答方式  
        Session.AUTO_ACKNOWLEDGE  消息自动签收  
        Session.CLIENT_ACKNOWLEDGE  客户端调用acknowledge方法手动签收  
        Session.DUPS_OK_ACKNOWLEDGE 不必必须签收,消息可能会重复发送 
        JMS规范的ack消息确认机制有一下四种,定于在session对象中:
AUTO_ACKNOWLEDGE = 1 :自动确认
CLIENT_ACKNOWLEDGE = 2:客户端手动确认 
DUPS_OK_ACKNOWLEDGE = 3: 自动批量确认
SESSION_TRANSACTED = 0:事务提交并确认
但是在activemq补充了一个自定义的ACK模式:
INDIVIDUAL_ACKNOWLEDGE = 4:单条消息确认 
        -->     
    </bean>




   <!--  配置消息队列监听者(Queue) -->
    <bean id="queueMessageListener" class="com.jjmc.client.filter.QueueMessageListener" />


<!--     显示注入消息监听容器(Queue),配置连接工厂,监听的目标是demoQueueDestination,监听器是上面定义的监听器 -->
    <bean id="queueListenerContainer"
          class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="demoQueueDestination" />
        <property name="messageListener" ref="queueMessageListener" />
    </bean>


</beans>

 

===================================================================================

4,web.xml的配置文件

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    
  <display-name>business-client</display-name>


  <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>


    <servlet>
        <servlet-name>business-client</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


<!-- 设置spring访问所有资源 -->
    <servlet-mapping>
        <servlet-name>business-client</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


<!-- Spring Config -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml;classpath:spring/applicationContext-ActiveMQ.xml</param-value>
</context-param>
<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


    <!-- Spring刷新Interceptor防止内存泄漏  -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>


<!-- 设置session 超时时间为20分钟 -->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
  <!-- 处理编码格式 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

=====================================================================

5,controller层

 

/**
 * 2017年11月20日下午8:09:48
 */
package com.jjmc.client.controller;


import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.jjmc.client.service.ConsumerService;
import com.jjmc.client.service.ProducerService;


/**
 *
 * @author huangtao
 * 2017年11月20日下午8:09:48
 * business-client
 * @parameter
 * TODO
 *
 */
@Controller
public class MessageController {
    private Logger logger = Logger.getLogger(MessageController.class);
    @Resource(name = "demoQueueDestination")
    private Destination destination;


    //队列消息生产者
    @Resource(name = "producerService")
    private ProducerService producer;


    //队列消息消费者
    @Resource(name = "consumerService")
    private ConsumerService consumer;


    @RequestMapping(value = "/SendMessage", method = RequestMethod.POST)
    @ResponseBody
    public void send(HttpServletRequest request, HttpServletResponse response,@RequestBody String msg) {
        logger.info(Thread.currentThread().getName()+"------------send to jms Start");
        producer.sendMessage(msg);
        logger.info(Thread.currentThread().getName()+"------------send to jms End");
    }


    @RequestMapping(value= "/ReceiveMessage",method = RequestMethod.GET)
    @ResponseBody
    public Object receive(){
        logger.info(Thread.currentThread().getName()+"------------receive from jms Start");
        TextMessage tm = consumer.receive(destination);
        logger.info(Thread.currentThread().getName()+"------------receive from jms End");
        return tm;
    }


}

 

===================================================================

6,生产者service

/**
 * 2017年11月20日下午8:08:24
 */
package com.jjmc.client.service;


import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;


import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;


/**
 *
 * @author huangtao
 * 2017年11月20日下午8:08:24
 * business-client
 * @parameter
 * TODO
 *
 */
@Service
public class ProducerService {


    @Resource(name="jmsTemplate")
    private JmsTemplate jmsTemplate;


    public void sendMessage(Destination destination,String msg){
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination.toString()+"发送消息---------------------->"+msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }


    public void sendMessage(String msg){
        String destination = jmsTemplate.getDefaultDestinationName();
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination+"发送消息---------------------->"+msg);
        jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }
}

 

========================================================================

7,消费者service

/**
 * 2017年11月20日下午8:09:12
 */
package com.jjmc.client.service;


import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;


import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;


/**
 *
 * @author huangtao
 * 2017年11月20日下午8:09:12
 * business-client
 * @parameter
 * TODO
 *
 */
@Service
public class ConsumerService {
    @Resource(name="jmsTemplate")
    private JmsTemplate jmsTemplate;


    public TextMessage receive(Destination destination){
        TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);
        try{
            System.out.println("从队列" + destination.toString() + "收到了消息:\t"
                    + textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return textMessage;
    }
}

======================================================================

8,监听器filter

注意:关于监听器,需要注意,如果配置了监听器,消息队列里的消息放入就会立即被监听到,就会自动被取出,不配置监听器,就可以调用取出的方法

/**
 * 2017年11月20日下午10:00:27
 */
package com.jjmc.client.filter;


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


/**
 *
 * @author huangtao
 * 2017年11月20日下午10:00:27
 * business-client
 * @parameter
 * TODO
 *
 */
public class QueueMessageListener implements MessageListener {
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
            System.out.println("QueueMessageListener监听到了文本消息:\t"
                    + tm.getText());
            //do something ...
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

 

=============================================================

 

ssm整合ActiveMQ

标签:就会   roc   res   intro   out   app   send   .post   项目   

原文地址:http://www.cnblogs.com/huangtao1927/p/7868676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!