RabbitMQ是一个受欢迎的消息代理,通常用于应用程序之间或者程序的不同组件之间通过消息来进行集成。本文简单介绍了如何使用 RabbitMQ,假定你已经配置好了rabbitmq服务器。 RabbitMQ是用Erlang,对于主要的编程语言都有驱动或者客户端。我们这里要用的是Java,所以先要获得Java客户端。。下面是Java客户端的maven依赖的配置。
|
像RabbitMQ这样的消息代理可用来模拟不同的场景,例如点对点的消息分发或者订阅/推送。我们的程序足够简单,有两个基本的组件,一个生产者用于产生消息,还有一个消费者用来使用产生的消息。 在这个例子里,生产者会产生大量的消息,每个消息带有一个序列号,另一个线程中的消费者会使用这些消息。 |
抽象类EndPoint:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
|
package
co.syntx.examples.rabbitmq;
import
java.io.IOException;
import
com.rabbitmq.client.Channel;
import
com.rabbitmq.client.Connection;
import
com.rabbitmq.client.ConnectionFactory;
/**
* Represents a connection with a queue
* @author syntx
*
*/
public
abstract
class
EndPoint{
protected
Channel channel;
protected
Connection connection;
protected
String endPointName;
public
EndPoint(String endpointName)
throws
IOException{
this
.endPointName = endpointName;
//Create a connection factory
ConnectionFactory factory =
new
ConnectionFactory();
//hostname of your rabbitmq server
factory.setHost(
"localhost"
);
//getting a connection
connection = factory.newConnection();
//creating a channel
channel = connection.createChannel();
//declaring a queue for this channel. If queue does not exist,
//it will be created on the server.
channel.queueDeclare(endpointName,
false
,
false
,
false
,
null
);
}
/**
* 关闭channel和connection。并非必须,因为隐含是自动调用的。
* @throws IOException
*/
public
void
close()
throws
IOException{
this
.channel.close();
this
.connection.close();
}
}
|
生产者:生产者类的任务是向队列里写一条消息。我们使用Apache Commons Lang把可序列化的Java对象转换成 byte 数组。commons lang的maven依赖如下: <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
| |
消费者:消费者可以以线程方式运行,对于不同的事件有不同的回调函数,其中最主要的是处理新消息到来的事件。
| |
Putting it together:在下面的测试类中,先运行一个消费者线程,然后开始产生大量的消息,这些消息会被消费者取走。
|