Java引用RabbitMQ快速入门

发布于:2025-05-10 ⋅ 阅读:(14) ⋅ 点赞:(0)

Java发送消息给MQ

    public void testSendMessage() throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 1.1.设置连接参数,分别是:主机名、端口号、vhost、用户名、密码
        factory.setHost("117.72.210.37");
        factory.setPort(5672);
        factory.setVirtualHost("bthost");
        factory.setUsername("admin");
        factory.setPassword("hURA6SxC6YrBFoqt");
        // 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.发送消息
        String message = "hello, rabbitmq!";
        channel.basicPublish("", queueName, null, message.getBytes());
        System.out.println("发送消息成功:【" + message + "】");

        // 5.关闭通道和连接
        channel.close();
        connection.close();

    }

消费者接收消息

    @RabbitListener(queues = "simple.queue")//指定要监听哪个队列
    public void listenSimpleQueueMessage(String msg){
        System.out.println("spring 消费者接收到消息 :【" + msg + "】");
        throw new RuntimeException("故意的");//MQ会一直投递消息
//        throw new MessageConversionException("故意的");//失败后返回reject不再投递
    }

实现一个队列绑定多个消费者

在这里插入图片描述

消息推送限制

在这里插入图片描述
如果没有设置限制话不管你上一条消息是否处理完,消费者会一直接收,设置厚只有处理完消息才会接受下一条。
在这里插入图片描述

Fanout交换机

在这里插入图片描述
在这里插入图片描述
将消息发送给交换机

    @Test
    public void testFanoutExchange() throws InterruptedException {
        //交换机名称
        String exchangeName = "itcast.fanout";
        String message = "hello, everyone";
        //这次是将消息发送到交换机,不再是队列
        rabbitTemplate.convertAndSend(exchangeName, "",message);
    }

在这里插入图片描述
接收消息

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1(String msg) {
        System.out.println("消费者1接收到Fanout消息:【" + msg + "】");
    }
    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2(String msg) {
        System.out.println("消费者2接收到Fanout消息:【" + msg + "】");
    }

路由的作用

在这里插入图片描述

Direct交换机

在这里插入图片描述

使用案例

在这里插入图片描述
交换机绑定
在这里插入图片描述

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue1"),
            exchange = @Exchange(name="itcast.direct",type = ExchangeTypes.DIRECT),
            key = {"red","blue"}
    ))
    public void listenDirectQueue1(String msg){
        System.out.println("消费者1接收到Direct消息:【" + msg + "】");
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "direct.queue2"),
            exchange = @Exchange(name="itcast.direct",type = ExchangeTypes.DIRECT),
            key = {"red","yellow"}
    ))
**    @Test
    public void testDirectExchange() {
        //交换机名称
        String exchangeName = "itcast.direct";
        String message = "hello, blue";
        //这次是将消息发送到交换机,不再是队列
        rabbitTemplate.convertAndSend(exchangeName, "red", message);
    }**

在这里插入图片描述
key是谁对应消费者就会接收到对应key的消息

Topic交换机

在这里插入图片描述
在这里插入图片描述
创建两个交换机
在这里插入图片描述
绑定交换机
在这里插入图片描述
发送消息

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(name = "topic.queue1"),
            exchange = @Exchange(value = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))

接收

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(name = "topic.queue1"),
            exchange = @Exchange(value = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者1接收到topic消息:【" + msg + "】");
    }

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(name = "topic.queue2"),
            exchange = @Exchange(value = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "#.news"
    ))

在这里插入图片描述

声明队列和交换机的方式

在这里插入图片描述
在这里插入图片描述
使用注解的方式来声明交换机绑定
注解及作用
@RabbitListener:将一个方法标记为 RabbitMQ 消息的监听器,让 Spring 知道这个方法要处理来自特定队列的消息。
@QueueBinding:定义了队列和交换器之间的绑定关系。
@Queue(name = “topic.queue1”):声明了一个名为 topic.queue1 的队列,如果该队列不存在,Spring 会自动创建。
@Exchange(value = “itcast.topic”, type = ExchangeTypes.TOPIC):指定了一个名为 itcast.topic 的主题(TOPIC)类型的交换器。主题交换器根据消息的路由键和绑定键来决定消息的路由。
key = “china.#”:绑定键使用了通配符 #,表示匹配以 china. 开头的任意路由键。也就是说,只要消息的路由键以 china. 开头,这个交换器就会把消息路由到 topic.queue1 队列。

    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(name = "topic.queue1"),
            exchange = @Exchange(value = "itcast.topic",type = ExchangeTypes.TOPIC),
            key = "china.#"
    ))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者1接收到topic消息:【" + msg + "】");
    }

会自动创建并绑定
在这里插入图片描述
直接发送就能收到了

    @Test
    public void testTopicExchange() {
        //交换机名称
        String exchangeName = "itcast.topic";
        String message = "日本天气";
        //这次是将消息发送到交换机,不再是队列
        rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
    }

MQ消息转换器

在这里插入图片描述
结果会变成一堆乱码
在这里插入图片描述
在这里插入图片描述
在main方法下添加消息转换器

package cn.itcast.mq;

import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
    /**
     * 序列化对象
     * @return
     */
    @Bean
    public MessageConverter jsonMessageConverter(){
        Jackson2JsonMessageConverter jjmc =new Jackson2JsonMessageConverter();
        jjmc.setCreateMessageIds(true);
        return jjmc;
    }
}

业务改造

在这里插入图片描述
消费者
在这里插入图片描述
生产者
在这里插入图片描述

生产者可靠性

在这里插入图片描述

设置重连

logging:
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS
  level:
      cn.itcast.mq: debug
spring:
  rabbitmq:
    host: 117.72.210.37
    port: 5672
    username: admin
    password: hURA6SxC6YrBFoqt
    virtual-host: bthost
    connection-timeout: 1s #设置MQ连接超时时间
    template:
      retry:
        enabled: true #开启超时重试机制
        initial-interval: 1000ms #失败后的初始等待时间
        multiplier: 1 #失败后下次等待市场倍数  下次等待时常:initial-interval * multiplier
        max-attempts: 3 #最大重试次数
#    【有道云笔记】MQ
#    https://note.youdao.com/s/DeiF6s2
    publisher-confirm-type: none
    publisher-returns: false

系统可靠性

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到