首页>代码>springboot+rabbitmq整合简单消息队列示例>/mq-demo/consumer/src/test/java/com/liangzi/mq/helloworld/ConsumerTest.java
package com.liangzi.mq.helloworld;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerTest {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 1.1.设置连接参数,分别是:主机名、端口号、vhost、用户名、密码
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 1.2.建立连接
        Connection connection = factory.newConnection();

        // 2.创建通道Channel
        Channel channel = connection.createChannel();

        // 3.创建队列
        String queueName = "simple.queue";
        channel.queueDeclare(queueName, false, false, false, null);

        // 4.订阅消息
        channel.basicConsume(queueName, true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 5.处理消息
                String message = new String(body);
                System.out.println("接收到消息:【" + message + "】");
            }
        });
        System.out.println("等待接收消息。。。。");
    }
}
最近下载更多
youwuzuichen  LV11 5月29日
微信网友_7134912998903808  LV15 2024年9月11日
zhujunnan  LV12 2024年3月19日
erqiu2013  LV18 2023年12月27日
Seaskye  LV14 2023年11月10日
shuangfu  LV25 2023年10月19日
杨豫川  LV12 2023年4月27日
sunlzh888888  LV29 2023年4月23日
quyiyi  LV3 2023年4月5日
最代码官方  LV168 2022年10月22日
最近浏览更多
andy_伟  LV7 8月18日
dane168  LV10 8月5日
youwuzuichen  LV11 5月29日
charleswang  LV7 2024年10月21日
微信网友_7134912998903808  LV15 2024年9月11日
TY0165  LV20 2024年6月17日
kenhomeliu  LV29 2024年4月30日
jc121140  LV3 2024年3月25日
zhujunnan  LV12 2024年3月5日
erqiu2013  LV18 2023年12月27日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友