发送端:
Send.java 连接到RabbitMQ(此时服务需要启动),发送一条数据,然后退出。
- package com.zhy.rabbit._01;
-
- 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 java.io.IOException
- {
-
-
-
- ConnectionFactory factory = new ConnectionFactory();
-
- factory.setHost("localhost");
-
- 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());
- System.out.println(" [x] Sent '" + message + "'");
-
- channel.close();
- connection.close();
- }
- }
值得注意的是队列只会在它不存在的时候创建,多次声明并不会重复创建。信息的内容是字节数组,也就意味着你可以传递任何数据。
接收端:Recv.java 不断等待服务器推送消息,然后在控制台输出。
- package com.zhy.rabbit._01;
-
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.Connection;
- import com.rabbitmq.client.ConnectionFactory;
- import com.rabbitmq.client.QueueingConsumer;
-
- public class Recv
- {
-
- private final static String QUEUE_NAME = "hello";
-
- public static void main(String[] argv) throws java.io.IOException,
- java.lang.InterruptedException
- {
-
- ConnectionFactory factory = new ConnectionFactory();
- factory.setHost("localhost");
- 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");
-
-
- QueueingConsumer consumer = new QueueingConsumer(channel);
-
- channel.basicConsume(QUEUE_NAME, true, consumer);
- while (true)
- {
-
- QueueingConsumer.Delivery delivery = consumer.nextDelivery();
- String message = new String(delivery.getBody());
- System.out.println(" [x] Received '" + message + "'");
- }
-
- }
- }
分别运行Send.java和Recv.java 顺序无所谓。前提RabbitMQ服务开启。
运行结果:
[x]Sent 'hello world!'
----------------------------------------
[*] Waiting for messages. To exitpress CTRL+C
[x] Received 'hello world!'