Apache Activemq 简明教程
Apache ActiveMQ - Overview
What is ActiveMQ?
ActiveMQ 是使用 Java 编写的开源消息代理。它完全符合 JMS 1.1 标准。它是由 Apache 软件基金会开发和维护的,并在 Apache 许可证下获得许可。它为企业级消息传递应用程序提供高可用性、可伸缩性、可靠性、性能和安全性。
ActiveMQ is an open source message broker written in Java. It’s fully compliant with JMS 1.1 standards. It is developed and maintained by Apache Software Foundation and is licensed under Apache license. It provides high availability, scalability, reliability, performance and security for enterprise level messaging applications.
JMS 是一个允许开发基于消息的系统的规范。ActiveMQ 充当消息代理,位于应用程序之间,并允许它们以异步且可靠的方式进行通信。
JMS is a specification that allows development of message based system. ActiveMQ acts as a broker of messages which sits in between applications and allows them to communicate in asynchronous and reliable way.
Types of Messaging
为了便于理解,下面解释了两种类型的消息传递选项。
There are two types of messaging options explained below for better understanding.
Point to Point
在这种通信方式中,代理只会向一个消费者发送消息,而其他消费者将等待从代理获得消息。没有消费者会收到相同的消息。
In this type of communication, the broker sends messages to only one consumer, while the other consumers will wait till they get the messages from the broker. No consumer will get the same message.
如果没有消费者,代理将一直持有消息,直到它得到消费者。这种通信方式也称为 Queue based communication ,生产者将消息发送到队列,并且只有一个消费者从队列中获取一条消息。如果有超过一个消费者,他们可能会获得下一条消息,但他们不会收到与其他消费者相同的消息。
If there are no consumers, the Broker will hold the messages till it gets a consumer. This type of communication is also called as Queue based communication where the Producer sends messages to a queue and only one consumer gets one message from the queue. If there is more than one consumer, they may get the next message but they won’t get the same message as the other consumer.
Publish/Subscribe
在这种通信方式中,代理会向所有活跃的消费者发送消息的同份副本。这种通信方式也称为 Topic based communication ,代理向所有为特定主题订阅的活跃消费者发送相同的消息。此模型支持单向通信,其中不期望对已传输的消息进行验证。
In this type of communication, the Broker sends same copy of messages to all the active consumers. This type of communication is also known as Topic based communication where broker sends same message to all active consumer who has subscribed for particular Topic. This model supports one-way communication where no verification of transmitted messages is expected.
Apache ActiveMQ - Environment Setup
本篇指导将引导你如何准备开发环境来开始使用 ActiveMQ 工作。它还将教你如何在设置 ActiveMQ 之前在计算机上设置 JDK、Maven 和 Eclipse −
This chapter will guide you on how to prepare a development environment to start your work with ActiveMQ. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up ActiveMQ −
Setup Java Development Kit (JDK)
你可以从 Oracle 的 Java 站点下载 SDK 的最新版本 − Java SE Downloads. 你在下载文件中可以找到安装 JDK 的说明,按照给定的说明进行安装和配置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。
You can download the latest version of SDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
如果您运行的是 Windows 且在 C:\jdk-11.0.11 中安装了 JDK,那么您将不得不把以下代码行放入您的 C:\autoexec.bat 文件中。
If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk-11.0.11;%PATH%
set JAVA_HOME=C:\jdk-11.0.11
或者,在 Windows NT/2000/XP 中,你必须右键单击我的电脑,选择属性 → 高级 → 环境变量。然后,你将不得不更新 PATH 值并单击确定按钮。
Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.
在 Unix(Solaris、Linux 等)中,如果 SDK 安装在 /usr/local/jdk-11.0.11 且您使用 C shell,那么您将不得不把以下代码行放入您的 .cshrc 文件中。
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.
setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11
或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.
Setup Eclipse IDE
本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。
All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.
要安装 Eclipse IDE,请从 www.eclipse.org/downloads/ 下载最新的 Eclipse 二进制文件。下载安装文件后,将二进制分发解压缩到合适的目录中。例如,在 Windows 中的 C:\eclipse 或 Linux/Unix 中的 /usr/local/eclipse 中,最后适当设置 PATH 变量。
To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe
Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
成功启动后,如果一切正常,它应该显示以下结果 −
After a successful startup, if everything is fine then it should display the following result −
Set Maven
在本教程中,我们使用 Maven 来运行和构建基于 Spring 的示例,以运行基于 ActiveMQ 的应用程序。按照 Maven - Environment Setup 安装 Maven。
In this tutorial, we are using maven to run and build the spring based examples to run ActiveMQ based applications. Follow the Maven - Environment Setup to install maven.
Download ActiveMQ
你可以从其官方页面下载最新稳定版的 ActiveMQ。按照 Download ActivMQ 下载 ActiveMQ。我们用了 2022 年 2 月 15 日发布的 5.13.4 版。将存档内容解压缩到你选择的文件夹中。我们已经解压缩到 F:/ → Apache → apache-activemq-5.16.4 中。
You can download the latest stable version of ActiveMQ from its official page. Follow the Download ActivMQ to download ActiveMQ. We’ve used the 5.13.4 released on Feb 15th, 2022. Extract the content of archive in the folder of your choice. We’ve extracted to F:/ → Apache → apache-activemq-5.16.4.
Apache ActiveMQ - Features
ActiveMQ 旨在为企业级消息传递应用程序提供高可用性、可伸缩性、可靠性、性能和安全性。以下是 ActiveMQ 的一些显著特性。
ActiveMQ is designed to provide high availability, scalability, reliability, performance and security for enterprise level messaging applications. Following are some of the salient features of ActiveMQ.
-
JMS Compliant − ActiveMQ is fully compliant with JMS 1.1 standards. JMS spec provides a standard mechanism for synchronous or asynchronous message delivery, once-and-only-once message delivery, message durability for subscribers, etc.
-
Connectivity Options − ActiveMQ supports HTTP/S, multicast, SSL, Stomp, TCP, UDP, XMPP, thus providing a wide range of options for connectivity and allows various systems to communicate using their choice of protocols.
-
Pluggable Architecture − ActiveMQ allows to choose a persistence mechanism and also provides options to customize security for authentication and authorization as per the application needs.
-
Multi-Platform − ActiveMQ provides client APIs for many popular languages like Java, C, C++, .NET, Perl, PHP, Python, Ruby etc. ActiveMQ Broker will run in JVM but clients can be written using any of the supported languages.
-
Broker Cluster − ActiveMQ allows to prepare a network of brokers for scalability and can support different types of topologies.
-
Features Rich − ActiveMQ provides many advanced features for both broker and clients and support Apache Camel.
-
Simple Administration Interface − ActiveMQ administration console is easy to use but still provides many powerful administration features.
Apache ActiveMQ - Running Broker Server
我们已下载 ActiveMQ - Environment Setup 中提到的最新版 ActiveMQ。现在,转到文件夹 F:/ → Apache → apache-activemq-5.16.4/bin 并输入以下命令。
We’ve downloaded the latest version of ActiveMQ as mentioned in ActiveMQ - Environment Setup. Now go to the folder F:/ → Apache → apache-activemq-5.16.4/bin and type the following command.
Output
您将看到类似的输出,ActiveMQ 将开始运行。
You’ll see the similar output and ActiveMQ will start running.
Java Runtime: Oracle Corporation 11.0.11 C:\Program Files\Java\jdk-11.0.11
Heap sizes: current=1048576k free=1041918k max=1048576k
JVM args: -Dcom.sun.management.jmxremote -Xms1G -Xmx1G -Djava.util.logging.config.file=logging.properties -Djava.security.auth.login.config=F:\Apache\apache-activemq-5.16.4\bin\..\conf\login.config -Dactivemq.classpath=F:\Apache\apache-activemq-5.16.4\bin\..\conf;F:\Apache\apache-activemq-5.16.4\bin\../conf;F:\Apache\apache-activemq-5.16.4\bin\../conf; -Dactivemq.home=F:\Apache\apache-activemq-5.16.4\bin\.. -Dactivemq.base=F:\Apache\apache-activemq-5.16.4\bin\.. -Dactivemq.conf=F:\Apache\apache-activemq-5.16.4\bin\..\conf -Dactivemq.data=F:\Apache\apache-activemq-5.16.4\bin\..\data -Djava.io.tmpdir=F:\Apache\apache-activemq-5.16.4\bin\..\data\tmp
Extensions classpath:
[F:\Apache\apache-activemq-5.16.4\bin\..\lib,F:\Apache\apache-activemq-5.16.4\bin\..\lib\camel,F:\Apache\apache-activemq-5.16.4\bin\..\lib\optional,F:\Apache\apache-activemq-5.16.4\bin\..\lib\web,F:\Apache\apache-activemq-5.16.4\bin\..\lib\extra]
ACTIVEMQ_HOME: F:\Apache\apache-activemq-5.16.4\bin\..
ACTIVEMQ_BASE: F:\Apache\apache-activemq-5.16.4\bin\..
ACTIVEMQ_CONF: F:\Apache\apache-activemq-5.16.4\bin\..\conf
ACTIVEMQ_DATA: F:\Apache\apache-activemq-5.16.4\bin\..\data
Loading message broker from: xbean:activemq.xml
INFO | Refreshing org.apache.activemq.xbean.XBeanBrokerFactory$1@53fe15ff: startup date [Sat Feb 26 12:50:18 IST 2022]; root of context hierarchy
INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[F:\Apache\apache-activemq-5.16.4\bin\..\data\kahadb]
INFO | PListStore:[F:\Apache\apache-activemq-5.16.4\bin\..\data\localhost\tmp_storage] started
INFO | Apache ActiveMQ 5.16.4 (localhost, ID:DESKTOP-86KD9FC-52669-1645860020983-0:1) is starting
INFO | Listening for connections at: tcp://DESKTOP-86KD9FC:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600
INFO | Connector openwire started
INFO | Listening for connections at: amqp://DESKTOP-86KD9FC:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600
INFO | Connector amqp started
INFO | Listening for connections at: stomp://DESKTOP-86KD9FC:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600
INFO | Connector stomp started
INFO | Listening for connections at: mqtt://DESKTOP-86KD9FC:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600
INFO | Connector mqtt started
INFO | Starting Jetty server
INFO | Creating Jetty connector
WARN | ServletContext@o.e.j.s.ServletContextHandler@4f966719{/,null,STARTING} has uncovered http methods for path: /
INFO | Listening for connections at ws://DESKTOP-86KD9FC:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600
INFO | Connector ws started
INFO | Apache ActiveMQ 5.16.4 (localhost, ID:DESKTOP-86KD9FC-52669-1645860020983-0:1) started
INFO | For help or more information please see: http://activemq.apache.org
INFO | ActiveMQ WebConsole available at http://127.0.0.1:8161/
INFO | ActiveMQ Jolokia REST API available at http://127.0.0.1:8161/api/jolokia/
Verification
现在,在您的浏览器中打开 http://127.0.0.1:8161/admin/ 。它会要求提供凭据。使用 admin/admin 作为用户名/密码,它将加载 ActiveMQ 管理控制台,您可以在其中查看队列、主题、连接等。
Now open http://127.0.0.1:8161/admin/ in your browser. It will ask for credentials. Use admin/admin as username/password and it will load the ActiveMQ admin console where you can check Queues, Topics, Connections etc.
Apache ActiveMQ - Admin Console
ActiveMQ 服务器启动并运行后。你可以使用管理控制台管理队列、主题、订户、连接、网络等。
Once ActiveMQ server is up and running. You can use the admin console to manage queues, topics, subscribers, connections, network etc.
在浏览器中打开 http://127.0.0.1:8161/admin/ 。它将询问凭据。使用 admin/admin 作为用户名/密码,它将加载 ActiveMQ 管理控制台,你可以在其中查看队列、主题、连接等。
Open http://127.0.0.1:8161/admin/ in your browser. It will ask for credentials. Use admin/admin as username/password and it will load the ActiveMQ admin console where you can check Queues, Topics, Connections etc.
Queue
单击队列选项卡,输入队列名称为 testQueue,然后单击创建按钮。现在你可以在列表中看到队列。
Click on Queue tab, enter a queue name as testQueue and click on create button. Now you can see the queue in the list.
Apache ActiveMQ - Producer Application
现在,我们来创建一个生产者应用程序,它将消息发送至 ActiveMQ 队列。
Now let’s create a producer application which will send message to the ActiveMQ Queue.
Create Project
使用 Eclipse,选择 File → New * → *Maven Project 。勾选 Create a simple project(skip archetype selection) ,然后单击下一步。
Using eclipse, select File → New * → *Maven Project. Tick the Create a simple project(skip archetype selection) and click Next.
按照以下所示输入详细信息 −
Enter the details, as shown below −
-
groupId − com.tutorialspoint
-
artifactId − producer
-
version − 0.0.1-SNAPSHOT
-
name − ActiveMQ Producer
单击“完成”按钮,将创建新项目。
Click on Finish button and a new project will be created.
pom.xml
现在,更新 pom.xml 的内容,以包含 ActiveMQ 的依赖关系。
Now update the content of pom.xml to include dependencies for ActiveMQ.
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.activemq</groupId>
<artifactId>producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ActiveMQ Producer</name>
<dependencies>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-jms-client</artifactId>
<version>0.40.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.fusesource.mvnplugins</groupId>
<artifactId>maven-uberize-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>uberize</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
现在,创建一个生产者类,它将消息发送至 ActiveMQ 队列。
Now create a Producer class which will send message to the ActiveMQ Queue.
package com.tutorialspoint.activemq;
import java.io.Console;
import java.util.Scanner;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public class Producer {
public static void main(String[] args) throws Exception {
// Create a connection to ActiveMQ JMS broker using AMQP protocol
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
Connection connection = factory.createConnection("admin", "password");
connection.start();
// Create a session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a queue
Destination destination = session.createQueue("MyFirstQueue");
// Create a producer specific to queue
MessageProducer producer = session.createProducer(destination);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.println("Enter message: ");
response = input.nextLine();
// Create a message object
TextMessage msg = session.createTextMessage(response);
// Send the message to the queue
producer.send(msg);
} while (!response.equalsIgnoreCase("Quit"));
input.close();
// Close the connection
connection.close();
}
}
生产者类将创建连接、启动会话、创建一个生产者,然后让用户输入消息。如果用户输入退出,则应用程序终止,否则将发送消息至队列。
Producer class creates a connection, starts the session, creates a producer and then asks user to enter message. If user enters quit then application terminates else it will send the message to the queue.
我们将在 ActiveMQ - Test Application 章节中运行此应用程序。
We’ll run this application in ActiveMQ - Test Application chapter.
Apache ActiveMQ - Consumer Application
现在,我们来创建一个使用者应用程序,它将从 ActiveMQ 队列中接收消息。
Now let’s create a consumer application which will receive message from the ActiveMQ Queue.
Create Project
使用 eclipse,选择 File → New → Maven Project 。勾选 创建简单项目(跳过原型选择),然后单击下一步。
Using eclipse, select File → New → Maven Project. Tick the *Create a simple project(skip archetype selection) * and click Next.
按照以下所示输入详细信息 −
Enter the details, as shown below −
-
groupId − com.tutorialspoint
-
artifactId − consumer
-
version − 0.0.1-SNAPSHOT
-
name − ActiveMQ Consumer
单击“完成”按钮,将创建新项目。
Click on Finish button and a new project will be created.
pom.xml
现在,更新 pom.xml 的内容,以包含 ActiveMQ 的依赖关系。
Now update the content of pom.xml to include dependencies for ActiveMQ.
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.activemq</groupId>
<artifactId>consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ActiveMQ Consumer</name>
<dependencies>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-jms-client</artifactId>
<version>0.40.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.fusesource.mvnplugins</groupId>
<artifactId>maven-uberize-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>uberize</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
现在,创建一个消费者类,它将从 ActiveMQ 队列接收消息。
Now create a Consumer class which will receive message from the ActiveMQ Queue.
package com.tutorialspoint.activemq;
import java.io.Console;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public class Consumer {
public static void main(String[] args) throws Exception {
// Create a connection to ActiveMQ JMS broker using AMQP protocol
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
Connection connection = factory.createConnection("admin", "password");
connection.start();
// Create a session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a queue
Destination destination = session.createQueue("MyFirstQueue");
// Create a consumer specific to queue
MessageConsumer consumer = session.createConsumer(destination);
Console c = System.console();
String response;
do {
// Receive the message
Message msg = consumer.receive();
response = ((TextMessage) msg).getText();
System.out.println("Received = "+response);
} while (!response.equalsIgnoreCase("Quit"));
// Close the connection
connection.close();
}
}
消费者类创建连接、启动会话、创建消费者,然后在有消息时从队列中接收消息。如果队列包含退出作为消息,则应用程序将终止,否则它将继续轮询队列以获取消息。
Consumer class creates a connection, starts the session, creates a consumer and then receives message from queue if there is any. If queue contains quit as message then application terminates else it will keep polling queue for messages.
我们将在 ActiveMQ - Test Application 章节中运行此应用程序。
We’ll run this application in ActiveMQ - Test Application chapter.
Apache ActiveMQ - Test Application
Start ActiveMQ Server
现在,我们来启动 ActiveMQ 服务器。转到文件夹 F:/ → Apache → apache-activemq-5.16.4/bin ,并输入以下命令。
Now let’s start the ActiveMQ Server. Go to the folder F:/ → Apache → apache-activemq-5.16.4/bin and type the following command.
Output
您将看到类似的输出,ActiveMQ 将开始运行。
You’ll see the similar output and ActiveMQ will start running.
...
INFO | Apache ActiveMQ 5.16.4 (localhost, ID:DESKTOP-86KD9FC-52669-1645860020983-0:1) started
INFO | For help or more information please see: http://activemq.apache.org
INFO | ActiveMQ WebConsole available at http://127.0.0.1:8161/
INFO | ActiveMQ Jolokia REST API available at http://127.0.0.1:8161/api/jolokia/
Start the Producer Application
在 eclipse 中,右键单击 Producer.java 源码,然后选择“Run As”(作为)> “Java 应用程序”。生产者应用程序将开始运行,您将看到如下输出:
In eclipse, right click on the Producer.java source, and select Run As > Java Application. Producer application will start running and you’ll see the output as follows −
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Enter message:
Start the Consumer Application
在 eclipse 中,右键单击 Consumer.java 源码,然后选择“Run As”(作为)> “Java 应用程序”。使用者应用程序将开始运行,您将看到如下输出:
In eclipse, right click on the Consumer.java source, and select Run As > Java Application. Consumer application will start running and you’ll see the output as follows −
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Send Message
在生产者控制台窗口中,键入 Hi 并按 enter 按钮发送消息。
In Producer console window, type Hi and press enter button to send the message.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Enter message:
Hi
Receive Message
在使用者控制台窗口中确认消息已收到。
Verify in Consumer console window, the message is received.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Received = Hi
发送退出作为消息以终止生产者和使用者控制台窗口会话。
Send Quit as message to terminate both producer and consumer console window sessions.
Verification
现在在浏览器中打开 http://127.0.0.1:8161/admin/ 。它会询问凭据。使用 admin/admin 作为用户名/密码,它将加载 ActiveMQ 管理控制台,您可以在其中查看队列以查看状态。它将显示已入队和已发送的 2 条消息。
Now open http://127.0.0.1:8161/admin/ in your browser. It will ask for credentials. Use admin/admin as username/password and it will load the ActiveMQ admin console where you can check Queues to check the status. It will show 2 messages enqueued and delivered.
Apache ActiveMQ - Publisher Application
现在,让我们创建一个发布者应用程序,它将把消息发送到 ActiveMQ 队列。
Now let’s create a publisher application which will send message to the ActiveMQ Queue.
Create Project
使用 Eclipse 选择 File → New * → *Maven Project 。勾选 创建简单项目(跳过原型选择),然后单击下一步。
Using eclipse, select File → New * → *Maven Project. Tick the *Create a simple project(skip archetype selection) * and click Next.
输入详细信息,如下所示:
Enter the details, as shown below−
-
groupId − com.tutorialspoint
-
artifactId − publisher
-
version − 0.0.1-SNAPSHOT
-
name − ActiveMQ Publisher
单击“完成”按钮,将创建新项目。
Click on Finish button and a new project will be created.
pom.xml
现在,更新 pom.xml 的内容,以包含 ActiveMQ 的依赖关系。
Now update the content of pom.xml to include dependencies for ActiveMQ.
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.activemq</groupId>
<artifactId>publisher</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ActiveMQ Publisher</name>
<dependencies>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-jms-client</artifactId>
<version>0.40.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.fusesource.mvnplugins</groupId>
<artifactId>maven-uberize-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>uberize</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
现在创建一个将消息发送到 ActiveMQ 主题以将其广播给所有订阅者的发布者类。
Now create a Publisher class which will send message to the ActiveMQ topic to broadcast it to all the subscribers.
package com.tutorialspoint.activemq;
import java.io.Console;
import java.util.Scanner;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public class Publisher {
public static void main(String[] args) throws Exception {
// Create a connection to ActiveMQ JMS broker using AMQP protocol
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
Connection connection = factory.createConnection("admin", "password");
connection.start();
// Create a session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a topic
Destination destination = session.createTopic("MyFirstTopic");
// Create a publisher specific to topic
MessageProducer publisher = session.createProducer(destination);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.println("Enter message: ");
response = input.nextLine();
// Create a message object
TextMessage msg = session.createTextMessage(response);
// Send the message to the topic
publisher.send(msg);
} while (!response.equalsIgnoreCase("Quit"));
input.close();
// Close the connection
connection.close();
}
}
生产者类创建一个连接,启动会话,创建一个生产者,然后要求用户输入消息。如果用户输入退出,则应用程序终止,否则它将把消息发送给该主题。
Producer class creates a connection, starts the session, creates a producer and then asks user to enter message. If user enters quit then application terminates else it will send the message to the topic.
我们将在 ActiveMQ - Test Application 章节运行此应用程序。
We’ll run this application in ActiveMQ - Test Application chapter.
Apache ActiveMQ - Subscriber Application
现在,让我们创建一个将从 ActiveMQ 主题接收消息的订阅者应用程序。
Now let’s create a subscriber application which will receive message from the ActiveMQ Topic.
Create Project
使用 eclipse,选择 File → New → Maven Project 。勾选 创建简单项目(跳过原型选择),然后单击下一步。
Using eclipse, select File → New → Maven Project. Tick the *Create a simple project(skip archetype selection) * and click Next.
按照以下所示输入详细信息 −
Enter the details, as shown below −
-
groupId − com.tutorialspoint
-
artifactId − subscriber
-
version − 0.0.1-SNAPSHOT
-
name − ActiveMQ Subscriber
单击“完成”按钮,将创建新项目。
Click on Finish button and a new project will be created.
pom.xml
现在,更新 pom.xml 的内容,以包含 ActiveMQ 的依赖关系。
Now update the content of pom.xml to include dependencies for ActiveMQ.
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.activemq</groupId>
<artifactId>subscriber</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ActiveMQ Subscriber</name>
<dependencies>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-jms-client</artifactId>
<version>0.40.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.fusesource.mvnplugins</groupId>
<artifactId>maven-uberize-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>uberize</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
现在创建一个将从 ActiveMQ 队列接收消息的订阅者类。
Now create a Subscriber class which will receive message from the ActiveMQ Queue.
package com.tutorialspoint.activemq;
import java.io.Console;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnectionFactory;
public class Subscriber {
public static void main(String[] args) throws Exception {
// Create a connection to ActiveMQ JMS broker using AMQP protocol
JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
Connection connection = factory.createConnection("admin", "password");
connection.start();
// Create a session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a topic
Destination destination = session.createTopic("MyFirstTopic");
// Create a subscriber specific to topic
MessageConsumer subscriber = session.createConsumer(destination);
Console c = System.console();
String response;
do {
// Receive the message
Message msg = subscriber.receive();
response = ((TextMessage) msg).getText();
System.out.println("Received = "+response);
} while (!response.equalsIgnoreCase("Quit"));
// Close the connection
connection.close();
}
}
订阅者类创建一个连接,启动会话,创建一个使用者,然后接收来自主题的消息(如果有)。如果该主题包含要退出的信息,则应用程序将终止,否则它将继续轮询队列以获取消息。
Subscriber class creates a connection, starts the session, creates a consumer and then receives message from topic if there is any. If topic contains quit as message then application terminates else it will keep polling queue for messages.
我们将在 ActiveMQ - Test Application 章节中多次运行此应用程序以创建多个订阅者。
We’ll run this application multiple times to create multiple subscribers in ActiveMQ - Test Application chapter.
Apache ActiveMQ - Test Application Topic
Start ActiveMQ Server
现在,我们来启动 ActiveMQ 服务器。转到文件夹 F:/ → Apache → apache-activemq-5.16.4/bin ,并输入以下命令。
Now let’s start the ActiveMQ Server. Go to the folder F:/ → Apache → apache-activemq-5.16.4/bin and type the following command.
Output
您将看到类似的输出,ActiveMQ 将开始运行。
You’ll see the similar output and ActiveMQ will start running.
...
INFO | Apache ActiveMQ 5.16.4 (localhost, ID:DESKTOP-86KD9FC-52669-1645860020983-0:1) started
INFO | For help or more information please see: http://activemq.apache.org
INFO | ActiveMQ WebConsole available at http://127.0.0.1:8161/
INFO | ActiveMQ Jolokia REST API available at http://127.0.0.1:8161/api/jolokia/
Start the Publisher Application
在 eclipse 中,鼠标右键单击 Publisher.java 源,然后选择以 Java 应用程序运行。Publisher 应用程序将开始运行,您会看到如下所示的输出:
In eclipse, right click on the Publisher.java source, and select Run As → Java Application. Publisher application will start running and you’ll see the output as follows −
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Enter message:
Start the Subscriber Application
在 eclipse 中,鼠标右键单击 Subscriber.java 源,然后选择以 Java 应用程序运行。Subscriber 应用程序将开始运行,您会看到如下所示的输出:
In eclipse, right click on the Subscriber.java source, and select Run As → Java Application. Subscriber application will start running and you’ll see the output as follows −
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Start another Subscriber Application
在 eclipse 中,再次鼠标右键单击 Subscriber.java 源,然后选择以 Java 应用程序运行。另一个 Subscriber 应用程序将开始运行,您会看到如下所示的输出:
In eclipse, again right click on the Subscriber.java source, and select Run As → Java Application. Another Subscriber application will start running and you’ll see the output as follows −
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Send Message
在 Publisher 控制台窗口中,输入 Hi 并按回车键以发送消息。
In Publisher console window, type Hi and press enter button to send the message.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Enter message:
Hi
Receive Message
在 Subscriber 控制台窗口中验证,消息在每个窗口中都能收到。
Verify in Subscriber console windows, the message is received in each window.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Received = Hi
发送退出作为消息以终止所有发布者和订阅者控制台窗口会话。
Send Quit as message to terminate all publisher and subscriber console window sessions.
Verification
现在,在您的浏览器中打开 http://127.0.0.1:8161/admin/ 。它会要求提供凭据。使用 admin/admin 作为用户名/密码,它将加载 ActiveMQ 管理控制台,您可以在其中查看主题以检查状态。它将显示入列和传递的多个消息。
Now open http://127.0.0.1:8161/admin/ in your browser. It will ask for credentials. Use admin/admin as username/password and it will load the ActiveMQ admin console where you can check Topics to check the status. It will show multiple messages enqueued and delivered.