RabbitMQ订阅模式

工具类:RabbitMQUtils

package com.example.ExchangeRabbit;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

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

public class RabbitMQUtils {

    public static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("chocoMoss");
        connectionFactory.setPassword("123456");
        Connection connection = connectionFactory.newConnection();
        return connection;
    }
}

提供者:PublishSubscribeProducer

获取连接
声明交换机:channel.exchangeDeclare()
声明队列:channel.queueDeclare()
队列绑定交换机:channel.queueBind()
消息体
发送:channel.basicPublish()

package com.example.ExchangeRabbit;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class PublishSubscribeProducer {

    /**
     * 订阅模式
     */

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        /**
         * 声明交换机
         * 参数1:交换机名称
         * 参数2:交换机类型,fanout,topic,direct,headers
         */
        channel.exchangeDeclare("fanout_exchange", BuiltinExchangeType.FANOUT);

        /**
         * 声明队列
         * 参数1:队列名称
         * 参数2:是否定义持久化队列
         * 参数3:是否读独占本次连接
         * 参数4:是否在不使用的时候自动删除队列
         * 参数5:队列其他参数
         */
        channel.queueDeclare("fanout_queue_1",true,false,false,null);
        channel.queueDeclare("fanout_queue_2",true,false,false,null);

        //队列绑定交换机
        channel.queueBind("fanout_queue_1","fanout_exchange","");
        channel.queueBind("fanout_queue_2","fanout_exchange","");

        //消息
        String message = "我就是来试试";

        /**
         * 参数1;交换机名称,如果没有指定则使用默认的Default Exchange
         * 参数2:路由key,简单模式可以传递队列名称
         * 参数3:消息其他属性
         * 参数:消息内容
         */
        channel.basicPublish("fanout_exchange","",null,message.getBytes());

        //关闭资源
        channel.close();
        connection.close();
    }
}

消费者:PublishSubscribeConsumerOne

创建连接
声明队列:channel.queueDeclare()
创建消费者:DefaultConsumer
处理消息:handleDelivery
获取路由key:envelope.getRoutingKey()
获取交换机:envelope.getExchange()
获取消息ID:envelope.getDeliveryTag()
获取消息
消息监听:channel.basicConsume();

package com.example.ExchangeRabbit;

import com.rabbitmq.client.*;

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

public class PublishSubscribeConsumerOne {

    /**
     * 订阅模式对象
     */
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建链接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("fanout_queue_1",true,false,false,null);

        //创建消费者,并设置消息处理
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                String routingKey = envelope.getRoutingKey();
                //交换机
                String exchange = envelope.getExchange();
                //消息ID
                long deliveryTag = envelope.getDeliveryTag();
                //收到消息
                String message = new String(body,"UTF-8");

                System.out.println("routingKey:"+routingKey+",exchange:"+exchange+",deliveryTag:"+deliveryTag+",message:"+message);
            }
        };
        //消息监听
        channel.basicConsume("fanout_queue_1",true,defaultConsumer);

        //关闭资源
//        channel.close();
//        connection.close();
    }
}

消费者:PublishSubscribeConsumerTwo

package com.example.ExchangeRabbit;

import com.rabbitmq.client.*;

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

public class PublishSubscribeConsumerTwo {

    /**
     * 订阅模式对象
     */
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建链接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("fanout_queue_2",true,false,false,null);

        //创建消费者,并设置消息处理
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                String routingKey = envelope.getRoutingKey();
                //交换机
                String exchange = envelope.getExchange();
                //消息ID
                long deliveryTag = envelope.getDeliveryTag();
                //收到消息
                String message = new String(body,"UTF-8");

                System.out.println("routingKey:"+routingKey+",exchange:"+exchange+",deliveryTag:"+deliveryTag+",message:"+message);
            }
        };
        //消息监听
        channel.basicConsume("fanout_queue_2",true,defaultConsumer);

        //关闭资源
//        channel.close();
//        connection.close();
    }
}

提供者提供消息
请添加图片描述
消费者获取消息
请添加图片描述
请添加图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值