在 上一篇文章 中,我们编写了一个简单的消息发送者(生产者),现在,让我们来编写一个对应的接收者(消费者),接收发送的消息。
建立消费者项目
在 IDEA 中新建一个 maven 项目,项目中所需要的依赖库及环境设置可以参考上一篇文章, 这里就不在赘述。
开发消息接收者
在 RabbitMQ 的 Java 客户端中, 接收消息的功能同样被封装在 Connection, Channel 这两个类中,所以我们同样需要通过 ConnectionFactory 去获取 Connection, 在通过 Connection 建立Channel。 与发送不同的是,通常在接收消息时,通常采用监听模式,这样我们的代码就会写出回调的方式。
看下面的代码:
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
| import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DeliverCallback;
public class HelloWorldReceiver {
private final static String QUEUE_NAME = "hello";
public void receive() throws Exception {
ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel();
DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received '" + message + "'"); };
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); }
}
|
在代码中,我们通过 Lambda 表达式,定义了一个回调接口: DeliverCallback, 并在该 Lambda 中处理收到的消息。
测试消息接收
在编写一个测试类: ReceiverTester, 用来测试消息接收,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import cn.com.hohistar.training.rabbitmq.receiver.HelloWorldReceiver; import org.junit.Test; import org.junit.jupiter.api.DisplayName;
@DisplayName("Message Receiver") public class ReceiverTester {
@Test @DisplayName("Receive Hello World Message") public void testHelloWorldReceiver() throws Exception {
HelloWorldReceiver receiver = new HelloWorldReceiver(); receiver.receive();
} }
|