7.md 9.2 KB
Newer Older
W
wizardforcel 已提交
1
# HornetQ 单体 – 基本的 JMS 消息传递示例
W
wizardforcel 已提交
2 3 4

> 原文: [https://howtodoinjava.com/hornetq/basic-jms-messaging-example-using-hornetq-stand-alone-server/](https://howtodoinjava.com/hornetq/basic-jms-messaging-example-using-hornetq-stand-alone-server/)

W
wizardforcel 已提交
5
[**HornetQ**](http://hornetq.jboss.org "hornetq") 是一个开放源代码项目,旨在构建多协议,可嵌入,非常高性能的集群异步消息传递系统。 HornetQ 支持 JMS 1.1 API,并且还定义了自己的消息传递 API,以实现最佳性能和灵活性。 HornetQ 一流的高性能日志以非持久消息传递通常看到的速度提供持久消息传递性能。 HornetQ 提供服务器复制和自动客户端故障转移功能,以消除服务器故障时丢失或重复的消息。
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
在上一篇文章中,我们了解了有关配置[**独立 hornetq 服务器和基本配置**](//howtodoinjava.com/hornetq/hornetq-stand-alone-server-example-using-maven/)的信息。 让我们继续举例。
W
wizardforcel 已提交
8 9 10

在本文中,我们将学习将 JMS 消息发送到 hornetq 服务器上的队列的机制,然后检索这些消息。

W
wizardforcel 已提交
11
步骤 1)使用以下命令创建一个 maven 项目并将其转换为 Eclipse Java 项目
W
wizardforcel 已提交
12 13 14 15 16 17 18 19 20 21

```java
mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=HornetQHelloWorld
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

 cd HornetQHelloWorld

 mvn eclipse:eclipse
```

W
wizardforcel 已提交
22
步骤 2)更新`pom.xml`文件并更新项目依赖项
W
wizardforcel 已提交
23

W
wizardforcel 已提交
24
**`pom.xml`**
W
wizardforcel 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

```java
<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.howtodoinjava</groupId>
  <artifactId>HornetQHelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>HornetQHelloWorld</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-core</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-jms</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-logging</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.hornetq</groupId>
     <artifactId>hornetq-transports</artifactId>
     <version>2.0.0.GA</version>
     <scope>compile</scope>
  </dependency>
  <dependency>
     <groupId>org.jboss.netty</groupId>
     <artifactId>netty</artifactId>
     <version>3.1.0.GA</version>
  </dependency>
  <dependency>
     <groupId>org.jboss.javaee</groupId>
     <artifactId>jboss-jms-api</artifactId>
     <version>1.1.0.GA</version>
     <scope>compile</scope>
  </dependency>

  </dependencies>
</project>

```

W
wizardforcel 已提交
84
步骤 3)将基本的 hornetq 配置文件放在类路径中。
W
wizardforcel 已提交
85

W
wizardforcel 已提交
86
**`hornetq-configuration.xml`**
W
wizardforcel 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

```java
<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
	<connectors>
		<connector name="netty-connector">
			<factory-class>org.hornetq.integration.transports.netty.NettyConnectorFactory
			</factory-class>
		</connector>
	</connectors>
	<acceptors>
		<acceptor name="netty-acceptor">
			<factory-class>org.hornetq.integration.transports.netty.NettyAcceptorFactory
			</factory-class>
		</acceptor>
	</acceptors>
	<security-enabled>false</security-enabled>
</configuration>

```

W
wizardforcel 已提交
109
步骤 4)配置连接器工厂,并将配置文件放置在`classpath`中。
W
wizardforcel 已提交
110

W
wizardforcel 已提交
111
**`hornetq-jms.xml`**
W
wizardforcel 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

```java
<?xml version="1.0"?>
<configuration xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hornetq">
	<!--the connection factory used by the example -->
	<connection-factory name="ConnectionFactory">
		<connectors>
			<connector-ref connector-name="netty-connector" />
		</connectors>
		<entries>
			<entry name="ConnectionFactory" />
		</entries>
	</connection-factory>
	<queue name="exampleQueue">
		<entry name="exampleQueue" />
	</queue>
</configuration>

```

W
wizardforcel 已提交
133
步骤 5)启动服务器并测试消息传递代码
W
wizardforcel 已提交
134

W
wizardforcel 已提交
135
**`HornetQMessageQueueDemo.java`**
W
wizardforcel 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

```java
package com.howtodoinjava;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.core.config.impl.FileConfiguration;
import org.hornetq.core.server.HornetQServer;
import org.hornetq.core.server.HornetQServers;
import org.hornetq.integration.transports.netty.NettyConnectorFactory;
import org.hornetq.integration.transports.netty.TransportConstants;
import org.hornetq.jms.server.JMSServerManager;
import org.hornetq.jms.server.impl.JMSServerManagerImpl;

public class HornetQMessageQueueDemo {

	static void startServer()
	{
		try
		  {
		     FileConfiguration configuration = new FileConfiguration();
		     configuration.setConfigurationUrl("hornetq-configuration.xml");
		     configuration.start();

		     HornetQServer server = HornetQServers.newHornetQServer(configuration);
		     JMSServerManager jmsServerManager = new JMSServerManagerImpl(server, "hornetq-jms.xml");
		     //if you want to use JNDI, simple inject a context here or don't call this method and make sure the JNDI parameters are set.
		     jmsServerManager.setContext(null);
		     jmsServerManager.start();
		     System.out.println("Server started !!");
		  }
		  catch (Throwable e)
		  {
		     System.out.println("Damn it !!");
		     e.printStackTrace();
		  }
	}

	public static void main(String[] args) throws Exception
	{
		//Start the server
		startServer();

		Connection connection = null;
		try 
		{
			// Step 1\. Directly instantiate the JMS Queue object.
			Queue queue = HornetQJMSClient.createQueue("exampleQueue");

			// Step 2\. Instantiate the TransportConfiguration object which
			// contains the knowledge of what transport to use,
			// The server port etc.

			Map<String, Object> connectionParams = new HashMap<String, Object>();
			connectionParams.put(TransportConstants.PORT_PROP_NAME, 5445);

			TransportConfiguration transportConfiguration = new TransportConfiguration(
																NettyConnectorFactory.class.getName(), connectionParams);

			// Step 3 Directly instantiate the JMS ConnectionFactory object
			// using that TransportConfiguration
			ConnectionFactory cf = HornetQJMSClient.createConnectionFactory(transportConfiguration);

			// Step 4.Create a JMS Connection
			connection = cf.createConnection();

			// Step 5\. Create a JMS Session
			Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

			// Step 6\. Create a JMS Message Producer
			MessageProducer producer = session.createProducer(queue);

			// Step 7\. Create a Text Message
			TextMessage message = session.createTextMessage("How to do in java dot com");

			System.out.println("Sent message: " + message.getText());

			// Step 8\. Send the Message
			producer.send(message);

			// Step 9\. Create a JMS Message Consumer
			MessageConsumer messageConsumer = session.createConsumer(queue);

			// Step 10\. Start the Connection
			connection.start();

			// Step 11\. Receive the message
			TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

			System.out.println("Received message: " + messageReceived.getText());
		} 
		finally
		{
			if (connection != null) {
				connection.close();
			}
		}
	}
}

Output in console:

22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: live server is starting..
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate warn
WARNING: AIO wasn't located on this platform, it will fall back to using pure Java NIO. If your platform is Linux, install LibAIO to enable the AIO journal
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: Using NIO Journal
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate warn
WARNING: Security risk! It has been detected that the cluster admin user and password have not been changed from the installation default. Please see the HornetQ user guide, cluster chapter, for instructions on how to do this.
22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: Started Netty Acceptor version 3.1.5.GA-r1772

Server started !!

22 Mar, 2013 2:23:36 PM org.hornetq.core.logging.impl.JULLogDelegate info
INFO: HornetQ Server version 2.0.0.GA (Hornet Queen, 113) started

Sent message: How to do in java dot com
Received message: How to do in java dot com

```

[**下载源代码**](https://docs.google.com/file/d/0B7yo2HclmjI4b21RNVZFZm55dEU/edit?usp=sharing "download source code")

**祝您学习愉快!**