初识RabbitMQ几种常见模式和API

目录

目标

准备

初识RabbitMQ

简介

支持的协议

常用的几种模式

Hello World模式

Work queues模式

Publish/Subscribe模式

Routing模式

Topics模式

代码演示

相关依赖

相关工具类

Hello World模式

Work queues模式

Publish/Subscribe模式

Routing模式

Topics模式

Java客户端API指南

项目地址


目标

掌握RabbitMQ几种常用模式的思想。本文将基于RabbitMQ官网提供相关的代码案例。


准备

  • Erlang环境;
  • 与Erlang版本对应的RabbitMQ;
  • 开放5672、15672端口。

官网:RabbitMQ Erlang版本要求https://www.rabbitmq.com/which-erlang.html


初识RabbitMQ

简介

  1. 支持多种消息传递协议、消息队列、传递确认、灵活的队列路由、多种交换类型。
  2. 使用BOSH、Chef、Docker 和 Puppet进行 部署。使用喜欢的编程语言开发跨语言消息传递,例如:Java、.NET、PHP、Python、JavaScript、Ruby、Go等。
  3. 分布式部署以获得高可用性和吞吐量;
  4. 可插拔认证、授权,支持TLS和LDAP。轻量级且易于部署在公共和私有云中。
  5. 支持持续集成、运营指标以及与其他企业系统集成 的各种工具和插件。用于扩展 RabbitMQ 功能 的灵活插件方法。
  6. HTTP-API、命令行工具和用于管理和监控RabbitMQ 的UI。

官网:RabbitMQ功能https://www.rabbitmq.com/


支持的协议

  1. AMQP 0-9-1
  2. STOMP
  3. MQTT
  4. AMQP 1.0
  5. HTTP and WebSockets(虽然HTTP并不是真正的消息传递协议,但 RabbitMQ可以通过三种方式通过HTTP 传输消息。)。

官网:RabbitMQ支持哪些协议?https://www.rabbitmq.com/protocols.html


常用的几种模式

官网:RabbitMQ教程https://www.rabbitmq.com/getstarted.html

Hello World模式

描述:一个生产者(发送者)发送一条消息,一个消费者(接收者)接收消息并打印出来。这是最简单的一种模式。

图解:其中P是生产者,C是消费者,红色矩形是队列。


Work queues模式

描述:即工作队列模式(任务队列),为避免执行复杂的业务而长时间等待,所以将部分任务封装为消息发送到队列。这些任务被这些消费者共享。

图解:其中P是生产者,C是消费者。


Publish/Subscribe模式

描述:即发布/订阅模式,生产者只能向交换器发送消息,消费者指定交换机订阅消息。

图解: 其中P是生产者,C是消费者,X是交换机(类型为fanout),生产者不直接把消息给队列,而是通过交换机将消息放入队列。


Routing模式

描述:即路由模式,通过routing_key(路由键或绑定键)有选择地接收消息。但该模式不能基于多个标准进行路由。

图解:其中P是生产者,C是消费者,X是交换机(类型为direct),其中C1的路由键只有error,所以C1只接收路由键为error的消息。


Topics模式

描述:即主题模式通配符模式,与路由模式相比,主题模式更灵活,交换机与队列之间通过通配符样式的路由键绑定。

通配符

  • *表示代替一个单词;
  • #表示代替零个或多个单词;

通配符示例

发送方的routingKey接收方1(*.henan.#)接收方2(*.henan.*)
china.hunan.changsh
china.hunan.changsha.tianxinqu
china.hunan.changsha.furongqu
china.hunan.yueyang
china.hunan.changde
china.henan.zhengzhou.jinshuiqu匹配
china.henan.hebi匹配匹配
china.henan.shangqiu匹配匹配
china.beijing

图解:其中P是生产者,C是消费者,X是交换机(类型为topic)


代码演示

相关依赖

        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>

相关工具类

package com.rabbit.utils;
public class RabbitConstant {
    public static final String QUEUE_SMS = "sms";
    public static final String QUEUE_BAIDU = "baidu";
    public static final String QUEUE_ALIBABA = "alibaba";
    public static final String EXCHANGE_FANOUT_AIR_CONDITION = "fanout_air_condition";
    public static final String EXCHANGE_DIRECT_AIR_CONDITION = "direct_air_condition";
    public static final String EXCHANGE_TOPIC_AIR_CONDITION = "topic_air_condition";
}
package com.rabbit.utils;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitUtils {
    private static ConnectionFactory connectionFactory = new ConnectionFactory();
    static {
        connectionFactory.setHost("我的IP");
        connectionFactory.setPort(5672);//5672是RabbitMQ的默认端口号
        connectionFactory.setUsername("用户名");
        connectionFactory.setPassword("密码");
        connectionFactory.setVirtualHost("虚拟机名称");
    }
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = connectionFactory.newConnection();
            return conn;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Hello World模式

生产者

package com.rabbit.helloworld;

import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

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

/**
 * @date 2022/1/18
 * @describe
 */
public class Producter {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        //参数一:队列名称
        //参数二:是否持久化
        //参数三:是否私有化,false表示所有消费者都可以访问,true表示只有第一次拥有它的消费者可以访问。
        //参数四:是否自动删除,false表示链接关闭以后不删除这个队列。
        //参数五:其他。
        channel.queueDeclare("helloworld", false, false, false, null);
        //发送消息
        //参数一:交换机(hello world模式可以不用交换机)
        //参数二:队列名称
        //参数三:额外属性
        //参数四:消息
        String msg="这是我发送的消息。";
        channel.basicPublish("", "helloworld", null, msg.getBytes());
        channel.close();
        connection.close();
        System.out.println("发送成功");
    }
}

消费者

package com.rabbit.helloworld;

import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @date 2022/1/18
 * @describe
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        //参数一:队列名称
        //参数二:是否持久化
        //参数三:是否私有化,false表示所有消费者都可以访问,true表示只有第一次拥有它的消费者可以访问。
        //参数四:是否自动删除,false表示链接关闭以后不删除这个队列。
        //参数五:其他。
        channel.queueDeclare("helloworld", false, false, false, null);
        //从MQ中获取数据
        //参数一:队列名称
        //餐宿二:false表示手动编程确认消息。
        //参数三:DefaultConsumer的子类的对象
        channel.basicConsume("helloworld",false,new Reciver(channel));
    }
}

DefaultConsumer的子类

package com.rabbit.helloworld;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * @author 陈天相
 * @date 2022/1/19
 * @describe
 */
class Reciver extends DefaultConsumer {
    private Channel channel;

    public Reciver(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String msg = new String(body);
        System.out.println(msg);
        System.out.println("消息的标签:" + envelope.getDeliveryTag());
        //只确认当前的消息
        channel.basicAck(envelope.getDeliveryTag(), false);
    }
}

Work queues模式

生产者

package com.rabbit.workqueues;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

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

/**
 * 短信发送方(生产者)
 */
public class OrderSystem {
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = RabbitUtils.getConnection();
            channel = connection.createChannel();
            //参数一:队列名称
            //参数二:是否持久化
            //参数三:是否私有化,false表示所有消费者都可以访问,true表示只有第一次拥有它的消费者可以访问。
            //参数四:是否自动删除,false表示链接关闭以后不删除这个队列。
            //参数五:其他。
            channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);

            for (int i = 1; i <= 100; i++) {
                SMS sms = new SMS("乘客" + i, "1890000000" + i, "您的车票已预订成功!");
                channel.basicPublish("", RabbitConstant.QUEUE_SMS, null, sms.toString().getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("发送数据成功。");
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
短信实体类
package com.rabbit.workqueues;

import lombok.Data;

/**
 * 短信实体类
 */
@Data
public class SMS {
    /*姓名*/
    private String name;
    /*手机*/
    private String mobile;
    /*内容*/
    private String content;

    public SMS(String name, String mobile, String content) {
        this.name = name;
        this.mobile = mobile;
        this.content = content;
    }
}

消费者1

package com.rabbit.workqueues;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 购票方1(消费者)
 */
public class SMSSender1 {

    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);
        //如果不写channel.basicQos(1),则自动MQ会将所有请求平均发送给所有消费者
        //channel.basicQos,MQ不再对消费者一次发送多个请求,而是消费者处理完一个消息后(确认后),在从队列中获取一个新的
        //处理完一个取一个,不同的服务器性能不同,A服务器消费消息后再次从队列中取出消息,此时B服务器还没有消费完。相当于按需分配。
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_SMS , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                System.out.println("购票方1(消费者)接收到:" + jsonSMS);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

消费者2

package com.rabbit.workqueues;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 购票方2(消费者)
 */
public class SMSSender2 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_SMS , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                System.out.println("购票方2(消费者)接收到:" + jsonSMS);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

消费者3

package com.rabbit.workqueues;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 购票方3(消费者)
 */
public class SMSSender3 {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_SMS , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                System.out.println("购票方3(消费者)接收到:" + jsonSMS);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

Publish/Subscribe模式

生产者

package com.rabbit.publishsubscribe;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @date 2022/1/21
 * @describe 消息生产者
 * 需要提前创建好交换机,且交换机类型=fanout
 */
public class Producter {
    public static void main(String[] args){
        Channel channel = null;
        Connection connection = null;
        try {
            connection = RabbitUtils.getConnection();
            channel = connection.createChannel();
            //第一个参数交换机名字   其他参数和之前的一样
            channel.basicPublish(RabbitConstant.EXCHANGE_FANOUT_AIR_CONDITION, "", null, "长沙空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。".getBytes());
            System.out.println("空气质量消息发送完毕。");
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(channel !=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

消费者1

package com.rabbit.publishsubscribe;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @date 2022/1/21
 * @describe
 */
public class Alibaba {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //声明队列信息
        channel.queueDeclare(RabbitConstant.QUEUE_ALIBABA, false, false, false, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key(暂时用不到)
        channel.queueBind(RabbitConstant.QUEUE_ALIBABA, RabbitConstant.EXCHANGE_FANOUT_AIR_CONDITION, "");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_ALIBABA , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("阿里巴巴收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

消费者2

package com.rabbit.publishsubscribe;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
 * @date 2022/1/21
 * @describe
 */
public class BaiDu {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //声明队列信息
        channel.queueDeclare(RabbitConstant.QUEUE_BAIDU, false, false, false, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key(暂时用不到)
        channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_FANOUT_AIR_CONDITION, "");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_BAIDU, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}

Routing模式

生产者

package com.rabbit.routing;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @date 2022/1/21
 * @describe 消息生产者
 * 需要提前创建好交换机,且交换机类型=direct
 */
public class Producter {
    public static Map<String,Object> getData(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("china.hunan.changsha","长沙空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changsha.tianxinqu","长沙天心区空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changsha.furongqu","长沙芙蓉区空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.yueyang","岳阳空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changde","常德空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.zhengzhou","郑州空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.hebi","鹤壁空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.shangqiu","商丘空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        return map;
    }
    public static void main(String[] args){
        Map<String, Object> map = getData();
        Channel channel = null;
        Connection connection = null;
        try {
            connection = RabbitUtils.getConnection();
            channel = connection.createChannel();
            for(String key:map.keySet()){
                System.out.println(map.get(key).toString());
                //第一个参数交换机名字
                //第二个参数作为 消息的routing key
                channel.basicPublish(
                        RabbitConstant.EXCHANGE_DIRECT_AIR_CONDITION,
                        key,
                        null,
                        map.get(key).toString().getBytes()
                );
            }
            System.out.println("空气质量消息发送完毕。");
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(channel !=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

消费者1

package com.rabbit.routing;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
 * @date 2022/1/21
 * @describe
 */
public class Alibaba {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //声明队列信息
        channel.queueDeclare(RabbitConstant.QUEUE_ALIBABA, false, false, false, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key
        channel.queueBind(RabbitConstant.QUEUE_ALIBABA, RabbitConstant.EXCHANGE_DIRECT_AIR_CONDITION, "china.hunan.changsha.tianxinqu");
        channel.queueBind(RabbitConstant.QUEUE_ALIBABA, RabbitConstant.EXCHANGE_DIRECT_AIR_CONDITION, "china.hunan.changsha.furongqu");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_ALIBABA , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("阿里巴巴收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

消费者2

package com.rabbit.routing;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @date 2022/1/21
 * @describe
 */
public class BaiDu {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //声明队列信息
        channel.queueDeclare(RabbitConstant.QUEUE_BAIDU, false, false, false, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key
        channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_DIRECT_AIR_CONDITION, "china.henan.zhengzhou");
        channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_DIRECT_AIR_CONDITION, "china.henan.hebi");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_BAIDU, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}

Topics模式

生产者

package com.rabbit.topic;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @date 2022/1/21
 * @describe 消息生产者
 * 需要提前创建好交换机,且交换机类型=direct
 */
public class Producter {
    public static Map<String,Object> getData(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("china.hunan.changsha","长沙空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changsha.tianxinqu","长沙天心区空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changsha.furongqu","长沙芙蓉区空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.yueyang","岳阳空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.hunan.changde","常德空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.zhengzhou.jinshuiqu","郑州空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.hebi","鹤壁空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.henan.shangqiu","商丘空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        map.put("china.beijing","北京空气指数:良。温馨提示:应减少户外活动,外出时佩戴口罩,敏感人群应尽量避免外出。");
        return map;
    }
    
    public static void main(String[] args){
        Map<String, Object> map = getData();
        Channel channel = null;
        Connection connection = null;
        try {
            connection = RabbitUtils.getConnection();
            channel = connection.createChannel();
            for(String key:map.keySet()){
                System.out.println(key+map.get(key).toString());
                //第一个参数交换机名字
                //第二个参数作为 消息的routing key
                channel.basicPublish(
                        RabbitConstant.EXCHANGE_TOPIC_AIR_CONDITION,
                        key,
                        null,
                        (key+map.get(key).toString()).getBytes()
                );
            }
            System.out.println("空气质量消息发送完毕。");
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(channel !=null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

消费者1

package com.rabbit.topic;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @date 2022/1/21
 * @describe
 */
public class Alibaba {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //为了方便测试不同的规则,这里先删除这个队列。
        channel.queueDelete(RabbitConstant.QUEUE_ALIBABA);
        //声明队列信息
        channel.queueDeclare(RabbitConstant.QUEUE_ALIBABA, false, false, true, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key
        channel.queueBind(RabbitConstant.QUEUE_ALIBABA, RabbitConstant.EXCHANGE_TOPIC_AIR_CONDITION, "*.henan.#");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_ALIBABA , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("阿里巴巴收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

消费者2

package com.rabbit.topic;

import com.rabbit.utils.RabbitConstant;
import com.rabbit.utils.RabbitUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @date 2022/1/21
 * @describe
 */
public class BaiDu {
    public static void main(String[] args) throws IOException {
        //获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        //获取虚拟连接
        final Channel channel = connection.createChannel();
        //为了方便测试不同的规则,这里先删除这个队列。
        channel.queueDelete(RabbitConstant.QUEUE_BAIDU);
        //参数一:队列名称
        //参数二:是否持久化
        //参数三:是否私有化,false表示所有消费者都可以访问,true表示只有第一次拥有它的消费者可以访问。
        //参数四:是否自动删除,false表示链接关闭以后不删除这个队列。
        //参数五:其他。
        channel.queueDeclare(RabbitConstant.QUEUE_BAIDU, false, false, false, null);
        //queueBind用于将队列与交换机绑定
        //参数1:队列名 参数2:交互机名  参数三:路由key
        channel.queueBind(RabbitConstant.QUEUE_BAIDU, RabbitConstant.EXCHANGE_TOPIC_AIR_CONDITION, "*.henan.*");
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUE_BAIDU , false , new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("百度收到空气质量信息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag() , false);
            }
        });
    }
}

Java客户端API指南

Java客户端API指南https://www.rabbitmq.com/api-guide.html


项目地址

项目地址https://download.csdn.net/download/qq_39706570/77151462

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值