超详细的 RabbitMq 的简单使用教程 Demo

<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>3.4.1</version>
</dependency>
  • 连接 RabbitMq 的 工具类 ConnectionUtil
/**
 * @author wangmx
 * 连接 RabbitMq  工具类
 */
public class ConnectionUtil {

    public static Connection getConnection() throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("1xx.xx.xx.xx8");
        //端口
        factory.setPort(5672);
        //设置账号信息
        //vhost(Virtual Host)
        factory.setVirtualHost("test");
        //用户名
        factory.setUsername("test");
        //密码
        factory.setPassword("test");
        // 通过工程获取连接
        Connection connection = factory.newConnection();
        return connection;
    }

}
  • 生产者
/**
 * @author wangmx
 * 生产者
 */
public class TestRabbitMq1 {

    private final static String QUEUE_NAME = "test_wangmx";

    public static void main(String[] args) throws Exception  {

        // 获取到连接以及mq通道
        Connection connections = ConnectionUtil.getConnection();
        // 从连接中创建通道
        Channel channel = connections.createChannel();

        // 声明(创建)队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 消息内容
        String message = "Hello World!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" 生产者 '" + message + "'");
        //关闭通道和连接
        channel.close();
        connections.close();

    }
}

控制台打印信息
在这里插入图片描述
管理页面 Queues 页面信息 ( 登陆 test 用户 去看否则看不到 )
在这里插入图片描述
点击 看看发送的 数据信息
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 消费者
/**
 * @author wangmx
 * 消费者
 */
public class TestRabbitMq2 {

    private final static String QUEUE_NAME = "test_wangmx";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        // 从连接中创建通道
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 定义队列的消费者
        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(" 消费者 '" + message + "'");
        }

    }

}

打印信息
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值