RabbitMQ五种消息模型

RabbitMQ支持的消息模型

https://www.rabbitmq.com/getstarted.html

环境搭建

创建一个Maven项目导入RabbitMQ依赖



    com.rabbitmq
    amqp-client
    5.7.2

创建ems用户,密码为123,创建VirtualHost /ems

Hello World 模型

在上图的模型中,有以下概念:

  • P:生产者,也就是要发送消息的程序
  • C:消费者:消息的接受者,会一直等待消息到来。
  • queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。

生产者

创建生产者Provider类,通过连接工厂对象获取连接,创建通道channel

//生产者
public class Provider {
    @Test
    public void testSendMessage() throws IOException, TimeoutException {
        //创建连接mq的连接工厂对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接rabbitmq的主机
        connectionFactory.setHost("localhost");
        //设置端口号
        connectionFactory.setPort(5672);
        //设置连接哪个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");

        //获取连接对象
        Connection connection = connectionFactory.newConnection();
        
        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应的消息队列
        //参数1:queue 队列名称 如果队列不存在则自动创建
        //参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
        //参数3:exclusive 是否独占队列 true 独占队列 false 不独占
        //参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
        channel.queueDeclare("hello",false,false,false,null);


        //发布消息
        //参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4;消息的具体内容
        channel.basicPublish("","hello", null,"hello rabbitmq".getBytes());

        channel.close();
        connection.close();
    }
}

消费者

channel.queueDeclare();与生产者保持一致,使用channel.basicConsume()接收消息,回调接口new DefaultConsumer(channel)重写handleDelivery()方法

//消费者
public class Customer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接mq的连接工厂对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接rabbitmq的主机
        connectionFactory.setHost("localhost");
        //设置端口号
        connectionFactory.setPort(5672);
        //设置连接哪个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");

        //获取连接对象
        Connection connection = connectionFactory.newConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应的消息队列--参数要和生产者保持对应,否则可能出现错误
        //参数1:queue 队列名称 如果队列不存在则自动创建
        //参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
        //参数3:exclusive 是否独占队列 true 独占队列 false 不独占
        //参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
        channel.queueDeclare("hello", false, false, false, null);

        //消费信息
        //参数1:消费哪个队列的信息 队列名称
        //参数2:开启消息的自动确认机制
        //参数3:消费时的回调接口
        channel.basicConsume("hello", true, new DefaultConsumer(channel) {

            //最后一个参数:消息队列中取出的信息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("new String(body)=" + new String(body));
            }
        });
    }
}

测速

首先启动消费者监听,然后在启动生产者发送消息。发送消息后消费者进行消费

参数说明

channel.queueDeclare("hello",false,false,false,null);

  • 参数1:queue 队列名称 如果队列不存在则自动创建
  • 参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
  • 参数3:exclusive 是否独占队列 true 独占队列 false 不独占
  • 参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除

channel.basicPublish("","aa", null,"hello rabbitmq".getBytes());

  • 参数1:交换机名称
  • 参数2:队列名称
  • 参数3:传递消息额外设置
  • 参数4;消息的具体内容

channel.basicConsume()

  • 参数1:消费哪个队列的信息 队列名称
  • 参数2:开启消息的自动确认机制
  • 参数3:消费时的回调接口

durable为ture只能实现队列持久化。若想要其中未消费的消息持久化channel.basicPublish()中参数3要设置为MessageProperties.PERSISTENT_TEXT_PLAIN

封装工具类

通过实现Hello World模型,我们可以发现存在了许多重复的代码。例如获取连接对象,关闭连接操作。我们将其封装成一个工具类 RabbitMQUtils,获取连接对象getConnection(),关闭资源closeConnectionAndChanel()

//工具类
public class RabbitMQUtils {
    //获取连接
    public static Connection getConnection() {
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            //设置连接rabbitmq的主机
            connectionFactory.setHost("localhost");
            //设置端口号
            connectionFactory.setPort(5672);
            //设置连接哪个虚拟主机
            connectionFactory.setVirtualHost("/ems");
            //设置访问虚拟主机的用户名和密码
            connectionFactory.setUsername("ems");
            connectionFactory.setPassword("123");
            return connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }
    //关闭连接和通道的方法
    public static void closeConnectionAndChanel(Channel channel, Connection connection) {
        try {
            //关闭通道
            if (channel != null) {
                channel.close();
            }
            //关闭连接
            if (connection != null) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

不过上述代码还是可以优化的,每次获取连接都需要创建一次工厂对象是没有必要的。相关认证资源也只需要加载一次即可。于是我们将代码优化

//工具类
public class RabbitMQUtils {
    //创建连接mq的连接工厂对象 属于重量级资源
    private static ConnectionFactory connectionFactory;

    //静态代码块 类加载时执行 只执行一次
    static {
        connectionFactory = new ConnectionFactory();
        //设置连接rabbitmq的主机
        connectionFactory.setHost("localhost");
        //设置端口号
        connectionFactory.setPort(5672);
        //设置连接哪个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
    }
    //获取连接
    public static Connection getConnection() {
        try {
            return connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭连接和通道的方法
    public static void closeConnectionAndChanel(Channel channel, Connection connection) {
        try {
            //关闭通道
            if (channel != null) {
                channel.close();
            }
            //关闭连接
            if (connection != null) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

}
//生产者
public class Provider {

    @Test
    public void testSendMessage() throws IOException, TimeoutException {
        //通过工具类获取连接对象
        Connection connection = RabbitMQUtils.getConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应的消息队列
        //参数1:queue 队列名称 如果队列不存在则自动创建
        //参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
        //参数3:exclusive 是否独占队列 true 独占队列 false 不独占
        //参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
        channel.queueDeclare("hello",true,false,false,null);

        //发布消息
        //参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4;消息的具体内容
        //channel.basicPublish("","aa", null,"hello rabbitmq".getBytes());
        channel.basicPublish("","hello", MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq".getBytes());

        //通过工具类关闭
        RabbitMQUtils.closeConnectionAndChanel(channel,connection);

    }
}

消费者同样使用工具类

//消费者
public class Customer {

    public static void main(String[] args) throws IOException, TimeoutException {

        //通过工具类获取连接对象
        Connection connection = RabbitMQUtils.getConnection();

        //获取连接中的通道
        Channel channel = connection.createChannel();

        //通道绑定对应的消息队列--参数要和生产者保持对应,否则可能出现错误
        //参数1:queue 队列名称 如果队列不存在则自动创建
        //参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
        //参数3:exclusive 是否独占队列 true 独占队列 false 不独占
        //参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
        channel.queueDeclare("hello", true, false, false, null);

        //消费信息
        //参数1:消费哪个队列的信息 队列名称
        //参数2:开启消息的自动确认机制
        //参数3:消费时的回调接口
        channel.basicConsume("hello", true, new DefaultConsumer(channel) {

            //最后一个参数:消息队列中取出的信息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("new String(body)=" + new String(body));
            }
        });
    }
}

封装成功!

Work Quene 模型

Work queues,也被称为(Task queues),任务模型。当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。

角色:

  • P:生产者:任务的发布者
  • C1:消费者-1,领取任务并且完成任务,假设完成速度较慢
  • C2:消费者-2:领取任务并完成任务,假设完成速度快

平均消费信息

生产者

public class Provider {

    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        //获取通道对象
        Channel channel = connection.createChannel();

        //通过通道声明队列
        channel.queueDeclare("work",true,false,false,null );

        //生产消息
        for (int i = 1; i <= 20; i++) {
            channel.basicPublish("","work",null,(i+"hello work queue").getBytes());
        }

        //关闭资源
         RabbitMQUtils.closeConnectionAndChanel(channel,connection);
    }
}

消费者

消费者1

public class Customer1 {

    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("work", true, false, false, null);

        //参数1:队列名称 参数2:消息自动确认 true 消费者自动向rabbitmq确认消息消费 false 不会自动确认消息
        channel.basicConsume("work", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-1:" + new String(body));
            }
        });
    }
}

消费者2

public class Customer2 {

    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare("work", true, false, false, null);

        //参数1:队列名称 参数2:消息自动确认 true 消费者自动向rabbitmq确认消息消费 false 不会自动确认消息
        channel.basicConsume("work", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-2:" + new String(body));
            }
        });
    }
}

测速

先分别启动消费者1和消费者2进行监听,再启动生产者生产消息

可以看到20条消息被依次平均消费了,轮询。

不过这种消费效果会导致一种问题。当某一个消费者出现了故障或者消费消息的时间过长,则会导致整个队列的消息都会变慢。类似木桶效应,因此我们需要一种能者多劳多得的消费消息策略。

消息自动确认机制

Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the consumer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We'll also lose all the messages that were dispatched to this particular worker but were not yet handled.

But we don't want to lose any tasks. If a worker dies, we'd like the task to be delivered to another worker.

我们在channel.basicConsume()中配置了消息自动确认。

不过开启自动确认机制还是存在隐患,例如上图消息消费者1接收到了5个消息后,自动确认了。则队列中的消息则会收到确认后删除。而消费者1消费3个消息后出现故障宕机,则为被消费的剩余两个消息则丢失了。

能者多劳多得

  • 关闭自动确认 channel.basicConsume(队列名, false,回调函数)
  • 道道每一次只消费一条信息 channel.basicQos(1);
  • 消费消息后手动确认 channel.basicAck(envelope.getDeliveryTag(),false);

消费者

public class Customer1 {

    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //每一次只消费一条消息
        channel.basicQos(1);

        channel.queueDeclare("work", true, false, false, null);

        //参数1:队列名称 参数2:消息自动确认 true 消费者自动向rabbitmq确认消息消费 false 不会自动确认消息
        channel.basicConsume("work", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者-1:" + new String(body));
                //手动确认信息
                //参数1:确认队列中哪个具体消息 参数2:是否开启多个消息同时确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

消费者1每次消费消息前先睡眠2秒。

public class Customer2 {

    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //每一次只消费一条消息
        channel.basicQos(1);

        channel.queueDeclare("work", true, false, false, null);

        //参数1:队列名称 参数2:消息自动确认 true 消费者自动向rabbitmq确认消息消费 false 不会自动确认消息
        channel.basicConsume("work", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-2:" + new String(body));
                //手动确认信息
                //参数1:确认队列中哪个具体消息 参数2:是否开启多个消息同时确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}

测试

两个消费者进行修改后,消费者1的消费速度远远小于消费者2 。此时看消费100条信息的结果。

消费者1只消费了1条消息,而消费者2消费了99条消息。实现了能者多劳多得多效果!

Fanout 模型

广播模型

角色:

  • P 生产者
  • C 消费者
  • X 交换机

在广播模式下,消息发送流程是这样的:

  • 可以有多个消费者
  • 每个消费者有自己的queue(队列)
  • 每个队列都要绑定到Exchange(交换机)
  • 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。
  • 交换机把消息发送给绑定过的所有队列
  • 队列的消费者都能拿到消息。实现一条消息被多个消费者消费

生产者

声明交换机channel.exchangeDeclare("logs", "fanout");参数1:交换机名称 参数2:交换机类型 fanout 广播类型

public class Provider {

    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明指定的的交换机
        //参数1:交换机名称 参数2:交换机类型 fanout 广播类型
        channel.exchangeDeclare("logs", "fanout");

        //发送消息
        channel.basicPublish("logs", "", null, "fanout type message".getBytes());

        //释放资源
        RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    }
}

消费者

消费者1

  • channel.exchangeDeclare("logs","fanout");通道绑定交换机
  • String queue = channel.queueDeclare().getQueue();获取临时队列
  • channel.queueBind(queue,"logs","");绑定交换机和队列
public class Customer1 {

    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道绑定交换机
        channel.exchangeDeclare("logs","fanout");

        //
        String queue = channel.queueDeclare().getQueue();

        //绑定交换机和队列
        channel.queueBind(queue,"logs","");

        //消费消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });
    }
}

消费者2和消费者3复制修改输入语句即可。

测试

首先启动消费者们,在启动生产者生产消息。

测试成功!

Direct 模型

在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。

在Direct模型下:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由key)
  • 消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey
  • Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息

图解:

  • P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
  • X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
  • C1:消费者,其所在队列指定了需要routing key 为 error 的消息
  • C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息

生产者

public class Provider {

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

        String exchangeName = "logs_direct";
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        //获取连接通道对象
        Channel channel = connection.createChannel();
        //通过通道声明交换机
        //参数1:交换机名称 参数2:direct 路由模式
        channel.exchangeDeclare(exchangeName,"direct");
        //发送消息
        String routingKey = "error";
        channel.basicPublish(exchangeName,routingKey,null,("这是direct模型发布的基于routingKey:【"+routingKey+"】").getBytes());

        //关闭资源
        RabbitMQUtils.closeConnectionAndChanel(channel,connection);

    }
}

消费者

消费者1

public class Customer1 {

    public static void main(String[] args) throws IOException {
        String exchangeName = "logs_direct";
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道绑定交换机
        channel.exchangeDeclare(exchangeName,"direct");

        //获取临时队列
        String queue = channel.queueDeclare().getQueue();

        //基于routingKey绑定交换机和队列
        channel.queueBind(queue,exchangeName,"error");

        //消费消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });
    }
}

消费者2

public class Customer2 {

    public static void main(String[] args) throws IOException {
        String exchangeName = "logs_direct";
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道绑定交换机
        channel.exchangeDeclare(exchangeName,"direct");

        //获取临时队列
        String queue = channel.queueDeclare().getQueue();

        //基于routingKey绑定交换机和队列
        channel.queueBind(queue,exchangeName,"info");
        channel.queueBind(queue,exchangeName,"error");
        channel.queueBind(queue,exchangeName,"warning");

        //消费消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2:"+new String(body));
            }
        });
    }
}

测试

生产者发送消息是的routingKey为error所以消费者1,和消费者2都能消费

当我们被生产者绑定当routingKey改为info时,此时只有消费者2才能消费

测试成功!

Topic 模型

Topic类型的ExchangeDirect相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符!这种模型Routingkey 一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert

生产者

public class Provider {

    public static void main(String[] args) throws IOException {
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //声明交换机以及交换机类型 topic
        channel.exchangeDeclare("topics","topic");

        String routingKey = "user.save.find";

        //发布消息
        channel.basicPublish("topics",routingKey,null,("这里是topic动态路由模型,routingKey:【"+routingKey+"】").getBytes());

        //释放资源
        RabbitMQUtils.closeConnectionAndChanel(channel,connection);

    }
}

消费者

消费者1

public class Customer1 {

    public static void main(String[] args) throws IOException {
        String exchangeName = "topics";
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道绑定交换机
        channel.exchangeDeclare(exchangeName,"topic");

        //获取临时队列
        String queue = channel.queueDeclare().getQueue();

        //基于routingKey绑定交换机和队列
        channel.queueBind(queue,exchangeName,"user.*");

        //消费消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者1:"+new String(body));
            }
        });
    }
}

消费者2

public class Customer2 {

    public static void main(String[] args) throws IOException {
        String exchangeName = "topics";
        //获取连接对象
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();

        //通道绑定交换机
        channel.exchangeDeclare(exchangeName,"topic");

        //获取临时队列
        String queue = channel.queueDeclare().getQueue();

        //基于routingKey绑定交换机和队列
        channel.queueBind(queue,exchangeName,"user.#");

        //消费消息
        channel.basicConsume(queue,true,new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者2:"+new String(body));
            }
        });
    }
}

测试

生产者绑定的routingKey为user.save.find,消费者1的routingKey为user.*,消费者2的routingKey为user.#。所以只符合消费者2。

测试成功!

你可能感兴趣的:(RabbitMQ五种消息模型)