Spring activemq 教程

本文详细介绍了一个基于ActiveMQ的消息发送与接收系统实现过程。包括使用Spring MVC搭建消息服务器、配置消息队列、实现消息生产和消费等功能。通过具体代码示例展示了如何在实际项目中集成ActiveMQ。
摘要由CSDN通过智能技术生成

1. 消息发送服务器 send 

SendController:

package controller;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ActiveMqDemo {
    @Autowired
    Producer producer;

    @RequestMapping("send")
    public void send() {
        for (int i = 0; i < 10; i++) {
            MyMessage myMessage = new MyMessage();
            System.out.println("生产第" + i + "条消息!");
            myMessage.setText("第" + i + "条消息!");
            producer.produce(myMessage);
        }
    }
}

Producer:

package controller;

import org.springframework.jms.core.JmsTemplate;

import javax.jms.Destination;

public class Producer {
    private JmsTemplate template;
    private Destination destination;

    public void produce(MyMessage message){
        template.convertAndSend(destination, message);
    }

    public JmsTemplate getTemplate() {
        return template;
    }

    public void setTemplate(JmsTemplate template) {
        this.template = template;
    }

    public Destination getDestination() {
        return destination;
    }

    public void setDestination(Destination destination) {
        this.destination = destination;
    }
}

MyMessage:

package controller;

import java.io.Serializable;

public class MyMessage implements Serializable {
    private static final long serialVersionUID = -4360789240260037588L;
    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String toString() {
        return text;
    }
}

applicationContex.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
			http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-autowire="byName" >

</beans>

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://activemq.apache.org/schema/core
       http://activemq.apache.org/schema/core/activemq-core-5.8.0.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">
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>
    <!--ActiveMQ 连接工厂方法1-->
    <!--<amq:connectionFactory id="jmsConnectionFactory" brokerURL="tcp://localhost:61616" userName="admin" password="admin" />-->

    <!-- ActiveMQ 连接工厂方法2 -->
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616 以及用户名,密码-->
    <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.179.129:61616" />
        <property name="userName" value="admin" />
        <property name="password" value="admin" />
        <property name="trustedPackages">
            <list>
                <value>controller</value>
            </list>
        </property>
    </bean>

    <!--定义消息队列方法1-->
    <!--<amq:queue name="destination" physicalName="queue" />-->

    <!--定义消息队列方法2-->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>queue</value>
        </constructor-arg>
    </bean>

    <!-- 定义JmsTemplate-->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsConnectionFactory"/>
    </bean>

    <!--定义生产者-->
    <bean id="producer" class="controller.Producer">
        <property name="template" ref="jmsTemplate" />
        <property name="destination" ref="destination"/>
    </bean>





</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
         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">
  <!-- 应用名称 -->
  <display-name>XueShenWeb</display-name>

  <!-- 加载所有的spring配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/applicationContex.xml
    </param-value>
  </context-param>
  <!-- 采用监听器加载 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- Spring配置 -->
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>  <!-- 拦截所有URL -->
  </servlet-mapping>

  <!-- 中文编码filter -->
  <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 以下配置的作用是 强行指定浏览器以gb2312编码格式打开HTM和HTML  -->
  <mime-mapping>
    <extension>htm</extension>
    <mime-type>text/html;charset=gb2312</mime-type>
  </mime-mapping>
  <mime-mapping>
    <extension>html</extension>
    <mime-type>text/html;charset=gb2312</mime-type>
  </mime-mapping>

</web-app>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Send</groupId>
  <artifactId>Send</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Send Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-all</artifactId>
      <version>5.14.3</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.7</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>Send</finalName>
      <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.3</version>
          </plugin>
          <plugin>
            <artifactId>maven-source-plugin</artifactId>
            <version>2.3</version>
            <executions>
              <execution>
                <phase>compile</phase>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <source>1.7</source>
              <target>1.7</target>
              <encoding>${project.build.sourceEncoding}</encoding>
              <showWarnings>true</showWarnings>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>maven-jetty-plugin</artifactId>
            <configuration>
              <contextPath>/</contextPath>
              <connectors>
                <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                  <port>8080</port>
                </connector>
              </connectors>
              <scanIntervalSeconds>10</scanIntervalSeconds>
            </configuration>
          </plugin>
      </plugins>
  </build>


</project>

消息接收服务器:

Consumer:

package controller;

public class Consumer {
    private int num;

    public void consume(MyMessage message) {
        System.out.println(num + "号消费" + message);
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://activemq.apache.org/schema/core
       http://activemq.apache.org/schema/core/activemq-core-5.8.0.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">
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>
    <!--ActiveMQ 连接工厂方法1-->
    <!--<amq:connectionFactory id="jmsConnectionFactory" brokerURL="tcp://localhost:61616" userName="admin" password="admin" />-->

    <!-- ActiveMQ 连接工厂方法2 -->
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    <!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616 以及用户名,密码-->
    <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.179.129:61616" />
        <property name="userName" value="admin" />
        <property name="password" value="admin" />
        <property name="trustedPackages">
            <list>
                <value>controller</value>
            </list>
        </property>
    </bean>

    <!--定义消息队列方法1-->
    <!--<amq:queue name="destination" physicalName="queue" />-->

    <!--定义消息队列方法2-->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>queue</value>
        </constructor-arg>
    </bean>

    <!-- 定义JmsTemplate-->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsConnectionFactory"/>
    </bean>



    <!--定义消费者-->
    <bean id="consumer" class="controller.Consumer">
        <property name="num" value="1"/>
    </bean>

    <!--定义监听器-->
    <bean id="mqListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
        <constructor-arg ref="consumer" />
        <property name="defaultListenerMethod" value="consume" />
    </bean>

    <!--定义监听器容器-->
    <bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsConnectionFactory" />
        <property name="destination" ref="destination" />
        <property name="messageListener" ref="mqListener" />
    </bean>
</beans>

web.xml pom.xml  相同

在linux-x86-64  目录下启动activemq 并查看进程

./activemq start

出现问题 

运行语句: sudo chmod 755 wrapper

在运行 启动语句: ./activemq start

demo下载地址:

https://download.csdn.net/download/maple980326/10588919

后台地址: http://192.168.179.128:8161/admin/

centOS 6.5关闭防火墙步骤

关闭命令:  service iptables stop 
        永久关闭防火墙:chkconfig iptables off

两个命令同时运行,运行完成后查看防火墙关闭状态 
        service iptables status

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值