activemq 教程

1、activemq介紹

1.1、介紹

ActiveMQ 是Apache出品,最流行的,能力強勁的開源消息總線。
主要特點:

  1. 多種語言和協議編寫客戶端。語言: Java, C, C++, C#, Ruby, Perl, Python, PHP。應用協議: OpenWire,Stomp REST,WS Notification,XMPP,AMQP
  2. 完全支持JMS1.1和J2EE 1.4規範 (持久化,XA消息,事務)
  3. 對Spring的支持,ActiveMQ可以很容易內嵌到使用Spring的系統裏面去,而且也支持Spring2.0的特性
  4. 通過了常見J2EE服務器(如 Geronimo,JBoss 4, GlassFish,WebLogic)的測試,其中通過JCA 1.5 resource adaptors的配置,可以讓ActiveMQ可以自動的部署到任何兼容J2EE 1.4 商業服務器上
  5. 支持多種傳送協議:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA
  6. 支持通過JDBC和journal提供高速的消息持久化
  7. 從設計上保證了高性能的集羣,客戶端-服務器,點對點
  8. 支持Ajax
  9. 支持與Axis的整合
  10. 可以很容易得調用內嵌JMS provider,進行測試

1.2、activemq消息形式

消息形式 特點
點對點 一個生產者和一個消費者一一對應
發佈/訂閱模式 即一個生產者產生消息並進行發送後,可以由多個消費者進行接收

2、activemq安裝

2.1、部署環境介紹

linux:centos7
activemq版本:5.15.11

2.2、安裝activemq步驟

2.2.1、上傳安裝包

cd /opt    #計劃activemq的安裝位置,進入該目錄
rz		   #文件上傳
tar -zxvf  apache-activemq-5.15.11-bin.tar.gz	#解壓安裝包

2.2.2、啓動activemq

cd  apache-activemq-5.15.11/bin		#進入解壓後文件夾的bin目錄
./acticemq start					#啓動activemq服務

2.2.3、查看activemq狀態

cd  apache-activemq-5.15.11/bin		#進入解壓後文件夾的bin目錄
./acticemq status					#查看activemq服務狀態

2.2.3、關閉activemq服務

cd  apache-activemq-5.15.11/bin		#進入解壓後文件夾的bin目錄
./acticemq stop						#關閉activemq服務狀態

2.2.4、服務啓動後頁面

網頁登錄默認端口:8161	,  默認登錄網址:http://127.0.0.1:8161/admin/
後臺訪問默認端口:61616

在這裏插入圖片描述
能進入上圖網頁說明activemq已經成功運行。

3、java操控activemq

3.1、activemq-queue(點對點模式)

3.1.1 queue(點對點)生產消息

package com.taotao.test;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;
import javax.jms.*;

public class TestActivemq {

    /**
     * 測試類 : 測試queue(點對點模式)下生產者發送消息
     * @throws Exception
     */
    @Test
    public void TestProviderForQueue() throws Exception {
        // 第一步:創建ConnectionFactory對象,需要指定服務端ip及端口號。
        ConnectionFactory connectFactory = new ActiveMQConnectionFactory("tcp://192.168.1.239:61616");
        // 第二步:使用ConnectionFactory對象創建一個Connection對象。
        Connection connection = connectFactory.createConnection();
        // 第三步:開啓連接,調用Connection對象的start方法。
        connection.start();
        // 第四步:使用Connection對象創建一個Session對象。
        //第一個參數:是否開啓事務。true:開啓事務,第二個參數忽略。
        //第二個參數:當第一個參數爲false時,纔有意義。消息的應答模式。1、自動應答2、手動應答。一般是自動應答。
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 第五步:使用Session對象創建一個Destination對象(topic、queue),此處創建一個Queue對象。
        //參數:隊列的名稱。
        Queue queue = session.createQueue("test-queue");
        // 第六步:使用Session對象創建一個Producer對象。
        MessageProducer producer = session.createProducer(queue);
        // 第七步:創建一個Message對象,創建一個TextMessage對象。
        /*
        也可以手工創建TextMessage對象
        TextMessage message = new ActiveMQTextMessage();
		message.setText("hello activeMq,this is my first test.");
		*/
        TextMessage textMessage = session.createTextMessage("hello world");
        // 第八步:使用Producer對象發送消息。
        producer.send(textMessage);
        // 第九步:關閉資源。
        producer.close();
        session.close();
        connection.close();
    }
}

3.1.2、queue(點對點)消費消息

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;
import javax.jms.*;


    @Test
	public void testQueueConsumer() throws Exception {
		// 第一步:創建一個ConnectionFactory對象。
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.168:61616");
		// 第二步:從ConnectionFactory對象中獲得一個Connection對象。
		Connection connection = connectionFactory.createConnection();
		// 第三步:開啓連接。調用Connection對象的start方法。
		connection.start();
		// 第四步:使用Connection對象創建一個Session對象。
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 第五步:使用Session對象創建一個Destination對象。和發送端保持一致queue,並且隊列的名稱一致。
		Queue queue = session.createQueue("test-queue");
		// 第六步:使用Session對象創建一個Consumer對象。
		MessageConsumer consumer = session.createConsumer(queue);
		// 第七步:接收消息。
		consumer.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message message) {
				try {
					TextMessage textMessage = (TextMessage) message;
					String text = null;
					//取消息的內容
					text = textMessage.getText();
					// 第八步:打印消息。
					System.out.println(text);
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		//等待鍵盤輸入
		System.in.read();
		// 第九步:關閉資源
		consumer.close();
		session.close();
		connection.close();
	}

3.3、activemq-topic(訂閱模式)

3.3.1 topic 生產消息

	@Test
	public void testTopicProducer() throws Exception {
		// 第一步:創建ConnectionFactory對象,需要指定服務端ip及端口號。
		// brokerURL服務器的ip及端口號
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.25.168:61616");
		// 第二步:使用ConnectionFactory對象創建一個Connection對象。
		Connection connection = connectionFactory.createConnection();
		// 第三步:開啓連接,調用Connection對象的start方法。
		connection.start();
		// 第四步:使用Connection對象創建一個Session對象。
		// 第一個參數:是否開啓事務。true:開啓事務,第二個參數忽略。
		// 第二個參數:當第一個參數爲false時,纔有意義。消息的應答模式。1、自動應答2、手動應答。一般是自動應答。
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 第五步:使用Session對象創建一個Destination對象(topic、queue),此處創建一個topic對象。
		// 參數:話題的名稱。
		Topic topic = session.createTopic("test-topic");
		// 第六步:使用Session對象創建一個Producer對象。
		MessageProducer producer = session.createProducer(topic);
		// 第七步:創建一個Message對象,創建一個TextMessage對象。
		/*
		 * TextMessage message = new ActiveMQTextMessage(); message.setText(
		 * "hello activeMq,this is my first test.");
		 */
		TextMessage textMessage = session.createTextMessage("hello activeMq,this is my topic test");
		// 第八步:使用Producer對象發送消息。
		producer.send(textMessage);
		// 第九步:關閉資源。
		producer.close();
		session.close();
		connection.close();
	}

3.3.2 topic消費消息

	@Test
	public void testTopicConsumer() throws Exception {
		// 第一步:創建一個ConnectionFactory對象。
		ConnectionFactory connectionFactory = new 				ActiveMQConnectionFactory("tcp://192.168.25.168:61616");
		// 第二步:從ConnectionFactory對象中獲得一個Connection對象。
		Connection connection = connectionFactory.createConnection();
		// 第三步:開啓連接。調用Connection對象的start方法。
		connection.start();
		// 第四步:使用Connection對象創建一個Session對象。
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 第五步:使用Session對象創建一個Destination對象。和發送端保持一致topic,並且話題的名稱一致。
		Topic topic = session.createTopic("test-topic");
		// 第六步:使用Session對象創建一個Consumer對象。
		MessageConsumer consumer = session.createConsumer(topic);
		// 第七步:接收消息。
		consumer.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message message) {
				try {
					TextMessage textMessage = (TextMessage) message;
					String text = null;
					// 取消息的內容
					text = textMessage.getText();
					// 第八步:打印消息。
					System.out.println(text);
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		System.out.println("topic的消費端。。。。。");
		// 等待鍵盤輸入
		System.in.read();
		// 第九步:關閉資源
		consumer.close();
		session.close();
		connection.close();
	}

4、Spring整合activemq

4.1、配置activemq整合spring,配置ConnectionFactory

配置對應xml文件,我將activemq配置文件單獨設置了一個:application-activemq.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
	
    <!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供 -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.25.168:61616" />
    </bean>
    <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory"
          class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory" />
    </bean>
    
</beans>

4.2、配置生產者

配置JMSTemplete對象,發送消息
配置Destinaction(queue點對點模式  或者  topic訂閱模式)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供 -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.25.168:61616" />
    </bean>
    <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory" />
    </bean>

    <!-- 配置生產者 -->
    <!-- Spring提供的JMS工具類,它可以進行消息發送、接收等 -->
    <bean id="jmsTemplete" class="org.springframework.jms.core.JmsTemplate" >
        <property name="connectionFactory" ref="connectionFactory"></property>
    </bean>

    <!--配置消息的Destination對象,確定消息隊列模式,-->
    <!--queue點對點模式-->
    <bean id="test-queue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg name="name" value="test-queue" ></constructor-arg>
    </bean>
    <!--topic訂閱模式-->
    <bean id="test-topic-item" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg name="name" value="test-item-topic" ></constructor-arg>
    </bean>

</beans>
測試生產者類
package com.taotao.test;

import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import javax.jms.*;

public class TestSpringActivemqProducter {

	@Autowired
	private JmsTemplate jmsTemplate;
	@Resource(name="test-topic-item")
	private Destination destination;

    public void testProducter(){
    	//發送消息
        jmsTemplate.send(destination, new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				//發送商品id
				TextMessage textMessage = session.createTextMessage(itemId + "");
				return textMessage;
			}
		});
    }

}

4.3、配置消費者

創建一個監聽類,這個類實現MessageListener接口
package com.taotao.search.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
消費者監聽類,實現MessageListener接口
*/
public class TestManageListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            System.out.println("消費者消費=" + text);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

配置xml文件,這是消費者監聽配置
<!-- 真正可以產生Connection的ConnectionFactory,由對應的 JMS服務廠商提供 -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.1.239:61616" />
    </bean>

    <!-- Spring用於管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目標ConnectionFactory對應真實的可以產生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory" />
    </bean>

    <!-- 配置生產者 -->
    <!-- Spring提供的JMS工具類,它可以進行消息發送、接收等 -->
    <bean id="jmsTemplete" class="org.springframework.jms.core.JmsTemplate" >
        <property name="connectionFactory" ref="connectionFactory"></property>
    </bean>

    <!--配置消息的Destination對象,確定消息隊列模式,-->
    <!--queue點對點模式-->
    <bean id="test-queue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg name="name" value="test-queue" ></constructor-arg>
    </bean>
    <!--topic訂閱模式-->
    <bean id="test-topic-item" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg name="name" value="test-item-topic" ></constructor-arg>
    </bean>

    <!--接收消息-->
    <!--配置監聽器-->
    <bean id="testMassageListener" class="com.taotao.search.listener.TestManageListener"></bean>

    <!--配置監聽器-->
    <bean class="org.springframework.jms.listener.DefaultMessageListenerContainer" >
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="test-queue" />
        <property name="messageListener" ref="testMassageListener" />
    </bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章