ActiveMQ入门实践

一、运行ActiveMQ程序

1、下载ActiveMQ软件包:

下载地址:http://activemq.apache.org/download-archives.html

2、下载后解压,在bin目录下根据计算机操作系统位数找到相应的wrapper.exe程序或者activemq.bat程序,双击运行。

3、浏览器访问http://localhost:8161/admin/,用户名和密码都是admin。


二、Spring整合ActiveMQ

1、从Maven仓库引入ActiveMQ相关包

<!-- 整合activeMQ到SpringMVC -->
    <!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-all -->
	<dependency>
	    <groupId>org.apache.activemq</groupId>
	    <artifactId>activemq-all</artifactId>
	    <version>5.13.2</version>
	</dependency>
     <!-- https://mvnrepository.com/artifact/org.springframework/spring-jms -->
     <dependency>
	   <groupId>org.springframework</groupId>
	   <artifactId>spring-jms</artifactId>
	   <version>4.3.15.RELEASE</version>
     </dependency>

刚接触ActiveMQ最好引入全部的activemq的包,避免漏包出现各种问题。

2、在文本项目中配置Spring整合ActiveMQ

其中包括配置ActiveMQ的连接,如果使用了连接池还需要配置连接池、配置Spring管理ActiveMQ的连接、配置JmsTemplate进行消息的发送和接收、配置消息发送模式(点对点、订阅/发布)、配置消息监听器监听生产者发布的消息以及配置管理监听器的容器。

可以将ActiveMQ的相关配置写在单独的文件中,有applicationContext.xml引入。

<import resource="spring-activemq-context.xml"/>

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:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/context/spring-context.xsd">
   <description>Spring容器管理ActiveMQ连接和使用 </description>
   <!-- 产生activemq连接的工厂 -->
   <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
   	<property name="brokerURL" value="tcp://localhost:61616"></property>
   </bean>
   
   <!-- 使用连接池 -->
   <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
   	<property name="connectionFactory" ref="targetConnectionFactory"/>
   	<property name="maxConnections" value="10"/>
   </bean>
   
   <!-- 配置Spring来管理ActiveMQ的连接 -->
   <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
   	<!-- <property name="targetConnectionFactory" ref="targetConnectionFactory"></property> -->
   	<!-- 使用连接池管理连接 -->
   	<property name="targetConnectionFactory" ref="pooledConnectionFactory"></property>
   </bean>
   
   <!-- 注入Spring提供的JMS工具类来进行消息的发送和接收 -->
   <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
   	<property name="connectionFactory" ref="connectionFactory"/>
   </bean>
   
   <!-- 配置消息的接收人,分为两种,一种是点对点式,一种是订阅/发布模式,即一对一还是多对多 -->
   <!-- 队列目的地,一对一 -->
   <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
   	<constructor-arg>
   		<value>queue</value>
   	</constructor-arg>
   </bean>
   <!-- 主题目的地,一对多 -->
   <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
   	<constructor-arg>
   		<value>topic</value>
   	</constructor-arg>
   </bean>
   
   <!-- 配置消息接收者 -->
   <!-- 配置消息接收者的监听器来监听接收的消息 -->
   <bean id="consumerMessageListener" class="com.teriste.activemq.jms.listener.ConsumerMessageListener">
   </bean>
   <!-- 配置消息监听器容器 -->
   <bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
   	<property name="connectionFactory" ref="connectionFactory"/>
   	<property name="destination" ref="queueDestination"></property>
   	<!-- <property name="destination" ref="topicDestination"></property> -->
   	<property name="messageListener" ref="consumerMessageListener"></property>
   </bean>
</beans>

其中如果使用了连接池管理连接需要引入commons-pool2的jar包。

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
	<dependency>
	    <groupId>org.apache.commons</groupId>
	    <artifactId>commons-pool2</artifactId>
	    <version>2.4.2</version>
	</dependency>

发布消息的业务类如下:

//ProducerService.java
import javax.jms.Destination;

public interface ProducerService
{
    public void sendMessage(Destination destination,final String message);
}
//ProducerServiceImpl.java
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;

import com.teriste.activemq.jms.service.ProducerService;

@Service("producerService")
public class ProducerServiceImpl implements ProducerService
{
    @Resource
    private JmsTemplate jmsTemplate;
    
    @Override
    public void sendMessage(Destination destination, final String message)
    {
        jmsTemplate.send(destination, new MessageCreator()
        {
            @Override
            public Message createMessage(Session session)
                throws JMSException
            {
                return session.createTextMessage(message);
            }
        });
    }
}

监听器负责监听发布者发布的消息,进行处理,实现如下:

// ConsumerMessageListener.java
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class ConsumerMessageListener implements MessageListener
{
    @Override
    public void onMessage(Message message)
    {
        TextMessage textMessage=(TextMessage)message;
        try
        {
            System.out.println("接收者收到消息:"+textMessage.getText());
            System.out.println("开始进行解析并调用service执行...");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

下面是生产者进行消息的发布:

//TestJMS.java
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import com.teriste.activemq.jms.entity.Content;
import com.teriste.activemq.jms.service.ProducerService;

@Controller
public class TestJMS
{
    @Autowired
    @Qualifier(value="producerService")
    private ProducerService producerService;
    
    @Autowired
    @Qualifier("queueDestination")
    private Destination destination;
    
    /*@Autowired
    @Qualifier("topicDestination")
    private Destination destination;*/
    
    public void testSend() throws Exception{
        List<Content> list=new LinkedList<Content>();
        Content content=new Content();
        content.setId(0);
        content.setName("article1");
        list.add(content);
        Content content1=new Content();
        content1.setId(1);
        content1.setName("article2");
        list.add(content1);
        Map<String, Object> mapEntity=new HashMap<String, Object>();
        mapEntity.put("user", list);
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("update", mapEntity);
        System.out.println("发送方发送内容为:"+JSONObject.fromObject(map).toString());
        //发送更新数据请求
        producerService.sendMessage(destination, JSONObject.fromObject(map).toString());
        System.out.println("生产者消息发送成功");
    }
}

测试类:

//AppTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.teriste.activemq.jms.controller.TestJMS;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext.xml")
public class AppTest
{
    @Autowired
    private TestJMS testJMS;
    @Test
    public void test(){
        try
        {
            testJMS.testSend();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

ActiveMQ默认的连接端口是61616,如果想要修改连接的端口,需要到conf目录下,修改activemq.xml中<transportConnectors>元素下的名称为openwire的transportConnector,修改相应uri即可。


猜你喜欢

转载自blog.csdn.net/dongyuxu342719/article/details/81016269