• 用maven和spring搭建ActiveMQ环境


    前面搭建过了简单的环境,这次用稍微实际一点的maven+spring+activemq来进行搭建

    准备:win7,eclipse,jdk1.8,tomcat8,maven3.5.2,activemq5.9

    开始:建maven项目就不说了,看结构图

    pom.xml

    <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.sinosoft</groupId>
      <artifactId>mq</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>mq Maven Webapp</name>
      <url>http://maven.apache.org</url>
       <properties>
               <springframework>4.2.1.RELEASE</springframework>
           </properties>
       
       
           <dependencies>
               <dependency>
                   <groupId>junit</groupId>
                   <artifactId>junit</artifactId>
                   <version>3.8.1</version>
                   <scope>test</scope>
               </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>
       
               <!-- spring -->
       
               <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.9.0</version>
               </dependency>
       
           </dependencies>
           <build>
               <finalName>mq</finalName>
           </build>
       </project>

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    
      
          <display-name>mq</display-name>
            <!-- contextConfigLocation 参数定义了要装入的 Spring 配置文件。 -->
          <context-param> 
              <param-name>contextConfigLocation</param-name>
              <param-value>
                  classpath:activemq.xml
              </param-value>
          </context-param>
          
          
          <listener>
              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
          
          <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:spring-mvc-dispatch.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>
          
          
          <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>forceRequestEncoding</param-name>
                  <param-value>true</param-value>
              </init-param>
              <init-param>
                  <param-name>forceResponseEncoding</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>

    activemq.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"
            >
        
        <context:component-scan base-package="com.sinosoft.activemq" />
        <mvc:annotation-driven />
            
        <amq:connectionFactory id="amqConnectionFactory" 
            brokerURL="tcp://127.0.0.1:61616" 
            userName="admin" 
            password="admin" />
        
        <!-- 配置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>sinosoft</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" />
            <property name="receiveTimeout" value="10000" />
            <!-- true是topic,false是queue,默认是false,此处显示写出false -->
            <property name="pubSubDomain" value="false" />
        </bean>
        
        <bean id="producerService" class="com.sinosoft.activemq.producer.ProducerService">
        </bean>
        
        <bean id="consumerService" class="com.sinosoft.activemq.consumer.ConsumerService">
        </bean>
        
     </beans>

    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: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-4.1.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
            
    <!-- 将base-package 目录下java文件中的所有@Component @Controller@Service等这些注解的类,则把这些类注册为bean -->
        <context:component-scan base-package="com.sinosoft.controller" />
    <!-- 自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。 -->
        <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=".jsp" />
        </bean>
    </beans>

    WelcomeController.java

    package com.sinosoft.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class WelcomeController {
    
        @RequestMapping(value="/welcome",method=RequestMethod.GET)
        public ModelAndView welcome(){
            System.out.println("-------------welcome-----------");
            ModelAndView mv = new ModelAndView();
            mv.setViewName("welcome");
            return mv;
        }
    }

    DemoController.java

    package com.sinosoft.controller;
    
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.annotation.Resource;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.TextMessage;
    import javax.management.MBeanServerConnection;
    import javax.management.remote.JMXConnector;
    import javax.management.remote.JMXConnectorFactory;
    import javax.management.remote.JMXServiceURL;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.sinosoft.activemq.consumer.ConsumerService;
    import com.sinosoft.activemq.producer.ProducerService;
    
    @Controller
    public class DemoController {
    
    //    @Resource(name = "demoQueueDestination")
        @Autowired
        private Destination demoQueueDestination;
    
    //    @Resource(name = "producerService")
        @Autowired
        private ProducerService producer;
    
    //    @Resource(name = "consumerService")
        @Autowired
        private ConsumerService consumer;
    
        @RequestMapping(value = "/producer", method = RequestMethod.GET)
        public ModelAndView producer() {
            System.out.println("--------------go producer");
    
            Date now = new Date();
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
            String time = sdf.format(now);
    
            System.out.println(time);
    
            ModelAndView mv = new ModelAndView();
    
            mv.addObject("time", time);
            mv.setViewName("jms_producer");
            return mv;
        }
    
        @RequestMapping(value = "/onsend", method = RequestMethod.POST)
        public ModelAndView producer(@RequestParam("message") String message) {
            System.out.println("---------send to jms");
            ModelAndView mv = new ModelAndView();
            producer.sendMessage(demoQueueDestination, message);
            mv.setViewName("welcome");
            return mv;
        }
    
        @RequestMapping(value = "/receive", method = RequestMethod.GET)
        public ModelAndView queue_receive() throws JMSException {
            System.out.println("-----------receive message");
            ModelAndView mv = new ModelAndView();
    
            TextMessage tm = consumer.receive(demoQueueDestination);
    
            if (tm == null) {
                mv.addObject("textMessage", "Queue is Empty");
            } else {
                mv.addObject("textMessage", tm.getText());
            }
            mv.setViewName("jms_receiver");
            return mv;
        }
    
        public ModelAndView jmsManager() throws IOException {
            System.out.println("--------------jms manager");
            ModelAndView mv = new ModelAndView();
    
            mv.setViewName("welcome");
    
            JMXServiceURL url = new JMXServiceURL("");
    
            JMXConnector connector = JMXConnectorFactory.connect(url);
            connector.connect();
            MBeanServerConnection connection = connector.getMBeanServerConnection();
    
            return mv;
        }
    
    }

    ProducerService.java

    package com.sinosoft.activemq.producer;
    
    import javax.annotation.Resource;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.Session;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.core.JmsTemplate;
    import org.springframework.jms.core.MessageCreator;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ProducerService {
    
    //    @Resource(name="jmsTemplate")
        @Autowired
        private JmsTemplate jmsTemplate;
        
        
        public void sendMessage(Destination destination,final String msg){
            System.out.println("Send " + msg + " to Destination " + destination.toString());
            
            MessageCreator messageCreator = new MessageCreator(){
    
                public Message createMessage(Session session) throws JMSException {
    
                    return session.createTextMessage(msg);
                }
                
            };
            
            jmsTemplate.send(destination, messageCreator);
        }
        
        
        public void sendMessage(final String msg){
            
            String destination = jmsTemplate.getDefaultDestinationName().toString();
            System.out.println("Send " + msg + " to Destination " + destination);
            MessageCreator messageCreator = new MessageCreator(){
    
                public Message createMessage(Session session) throws JMSException {
                    // TODO Auto-generated method stub
                    return session.createTextMessage(msg);
                }
                
            };
            
            jmsTemplate.send(messageCreator);
        }
    }

    ConsumerService.java

    package com.sinosoft.activemq.consumer;
    
    import javax.annotation.Resource;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.TextMessage;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jms.core.JmsTemplate;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ConsumerService {
    
    //    @Resource(name = "jmsTemplate")
        @Autowired
        private JmsTemplate jmsTemplate;
    
        public TextMessage receive(Destination destination) {
            TextMessage tm = (TextMessage) jmsTemplate.receive(destination);
            if (tm != null) {
                try {
                    System.out.println("Get Message: " + tm.getText() + " from Destination " + destination.toString());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            return tm;
        }
    
    }

    好了,先把activemq运行上

     接着运行tomcat后进入页面看效果,这里只看点对点传输

    控制台打印日志

     最后说一说可能遇上的问题及解决方式

    如果没有上图第五行这个,可能会报找不到监听器的错误,只需自己添上就行,add->java build path enties->maven dependencies

    如果第一次tomcat没有运行成功中途报错了,下一次就算代码正确了,或者配置都正确了也有可能会运行不起来,因为tomcat有缓存,所以清除tomcat下work下所有文件很有必要.其次把webapp里面无关紧要的项目都清除掉,这会大大降低tomcat的启动时间.

     

  • 相关阅读:
    EC++学习笔记(五) 实现
    EC++学习笔记(三) 资源管理
    EC++学习笔记(一) 习惯c++
    EC++学习笔记(六) 继承和面向对象设计
    STL学习笔记(三) 关联容器
    STL学习笔记(一) 容器
    背包问题详解
    EC++学习笔记(二) 构造/析构/赋值
    STL学习笔记(四) 迭代器
    常用安全测试用例
  • 原文地址:https://www.cnblogs.com/goujh/p/8532439.html
Copyright © 2020-2023  润新知