1、介绍
RabbitMQ 是信息传输的中间者。本质上,他从生产者(producers)接收消息,转发这些消息给消费者(consumers).换句话说,他能够按根据你指定的规则进行消息转发、缓冲、和持久化。
RabbitMQ 的一些常见的术语:
Producing意味着无非是发送。一个发送消息的程序是一个producer(生产者)。一般用下图表示Producer:
Queue(队列)类似邮箱。依存于RabbitMQ内部。虽然消息通过RabbitMQ在你的应用中传递,但是它们只能存储在queue中。队列不受任何限制,可以存储任何数量的消息—本质上是一个无限制的缓存。很多producers可以通过同一个队列发送消息,相同的很多consumers可以从同一个队列上接收消息。一般用下图表示队列:
Consuming(消费)类似于接收。consumer是基本属于等待接收消息的程序。一般使用下图表示Consumer:
注意:producer(生产者),consumer(消费者),broker(RabbitMQ服务)并不需要部署在同一台机器上,实际上在大多数实际的应用中,也不会部署在同一台机器上。
2、Java入门实例
一个producer发送消息,一个接收者接收消息,并在控制台打印出来。如下图:
发送端:Send.java 连接到RabbitMQ(此时服务需要启动),发送一条数据,然后退出。
import
com.rabbitmq.client.Channel;
import
com.rabbitmq.client.Connection;
import
com.rabbitmq.client.ConnectionFactory;
public
class
Send {
private
final
static
String QUEUE_NAME =
"hello"
;
public
static
void
main(String[] argv)
throws
Exception {
ConnectionFactory factory =
new
ConnectionFactory();
factory.setHost(
"192.168.1.8"
);
factory.setUsername(
"root"
);
factory.setPassword(
"123456"
);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,
false
,
false
,
false
,
null
);
String message =
"Hello World!"
;
channel.basicPublish(
""
, QUEUE_NAME,
null
, message.getBytes(
"UTF-8"
));
System.out.println(
" [x] Sent '"
+ message +
"'"
);
channel.close();
connection.close();
}
}
|
值得注意的是队列只会在它不存在的时候创建,多次声明并不会重复创建。信息的内容是字节数组,也就意味着你可以传递任何数据。
接收端:Recv.java 不断等待服务器推送消息,然后在控制台输出。
import
com.rabbitmq.client.*;
import
java.io.IOException;
public
class
Recv {
private
final
static
String QUEUE_NAME =
"hello"
;
public
static
void
main(String[] argv)
throws
Exception {
ConnectionFactory factory =
new
ConnectionFactory();
factory.setHost(
"192.168.1.8"
);
factory.setUsername(
"root"
);
factory.setPassword(
"123456"
);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,
false
,
false
,
false
,
null
);
System.out.println(
" [*] Waiting for messages. To exit press CTRL+C"
);
Consumer consumer =
new
DefaultConsumer(channel) {
@Override
public
void
handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte
[] body)
throws
IOException {
String message =
new
String(body,
"UTF-8"
);
System.out.println(
" [x] Received '"
+ message +
"'"
);
}
};
channel.basicConsume(QUEUE_NAME,
true
, consumer);
}
}
|
分别运行Send.java和Recv.java 顺序无所谓。前提RabbitMQ服务开启。
运行结果:
[x]Sent 'hello world!'
----------------------------------------
[*] Waiting for messages. To exitpress CTRL+C
[x] Received 'hello world!'