* RabbitMQ 集成springboot 与 异步解耦实战

目录

  • RabbitMQ
    • 消息中间件入门,AMQP 与 RabbitMQ
    • RabbitMQ中消息发布 与 权衡
    • RabbitMQ 中消息消费权衡 及 消息属性
    • RabbitMQ 异步处理实战
    • RabbitMQ 管理与高可用集群
  • Kafka
    • Kafka 入门,生产者 和 消费者实战
    • Kafka 高级进阶,消费者分区再均衡
    • 深入理解Kafka的内部机制
    • Kafka 集群及流计算实战
  • RocketMQ
    • RocketMQ 入门
    • 玩转RocketMQ 中的消息发送 与 消费
    • RocketMQ 的高级特性
    • RocketMQ 的存储以及高可用集群
    • RocketMQ限时订单实战

RabbitMQ 集成springboot 与 异步处理实战

1、集成springboot

1.1 添加 maven 依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!--springboot集成rabbitmq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

1.2 配置基本参数

server.port=8080
spring.application.name=springboot-rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
# 发送方确认
spring.rabbitmq.publisher-confirms=true
# 虚拟主机
spring.rabbitmq.virtual-host=/

1.3 配置类

在配置类中声明

  • 创建连接工厂
  • 声明 RabbitTemplate
  • 声明交换器
  • 声明队列
  • 设置绑定关系
  • 设置失败通知方法,发送者确认方法,失败者确认方法。
package com.h.rabbitmq.springboot.config;

import com.h.rabbitmq.springboot.RmConst;
import com.h.rabbitmq.springboot.hello.UserReceiver;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 15:10
 */
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.host}")
    private String addresses;
    @Value("${spring.rabbitmq.port}")
    private String port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;
    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms;

    @Autowired
    private UserReceiver userReceiver;


    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(addresses + ":" + port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        // 如果要进行消息回调,则这里必须要设置为true
        connectionFactory.setPublisherConfirms(publisherConfirms);

        return connectionFactory;
    }

    /**rabbitAdmin 类封装对RabbitMQ的管理操作*/
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public RabbitTemplate newRabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        // 开启生产者确认
        rabbitTemplate.setMandatory(true);
        // 发送方确认
        rabbitTemplate.setConfirmCallback(confirmCallback());
        // 失败回调
        rabbitTemplate.setReturnCallback(returnCallback());
        return rabbitTemplate;
    }

    /**生产者失败通知(无法路由)*/
    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return new RabbitTemplate.ReturnCallback(){
            @Override
            public void returnedMessage(Message message,
                                        int replyCode,
                                        String replyText,
                                        String exchange,
                                        String routingKey) {
                System.out.println("无法路由的消息,需要考虑另外处理。");
                System.out.println("Returned replyText:" + replyText);
                System.out.println("Returned exchange:" + exchange);
                System.out.println("Returned routingKey:" + routingKey);
                System.out.println("Returned Message:" + new String(message.getBody()));
            }
        };
    }

    /**生产者发送确认*/
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData,
                                boolean ack,
                                String cause) {
                if (ack) {
                    System.out.println("发送者确认发送mq成功");
                } else {
                    System.out.println("发送者发送给mq失败,考虑重发:" + cause);
                }
            }
        };
    }

    /**消费者确认*/
    @Bean
    public SimpleMessageListenerContainer messageContainer() {
        SimpleMessageListenerContainer container
                = new SimpleMessageListenerContainer(connectionFactory());
        // 绑定队列
        container.setQueues(userQueue());
        // 设置手动提交
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        // 消费确认的方法
        container.setMessageListener(userReceiver);
        return container;
    }

    // =======================使用了RabbitMQ系统缺省的交换器============================
    /**申明队列,这里没有绑定交换器,会默认使用direct交换器*/
    @Bean
    public Queue helloQueue() {
        return new Queue(RmConst.QUEUE_HELLO);
    }

    @Bean
    public Queue userQueue() {
        return new Queue(RmConst.QUEUE_USER);
    }

    // =======================以下是验证topic Excahnge============================
    /**申明交换器*/
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(RmConst.EXCHANGE_TOPIC);
    }

    @Bean
    public Queue queueEmailMessage() {
        return new Queue(RmConst.QUEUE_TOPIC_EMAIL);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindingEmailExchangeMessage() {
        return BindingBuilder
                .bind(queueEmailMessage())
                .to(topicExchange())
                .with("h.*.email");
    }

    @Bean
    public Queue queueUserMessages() {
        return new Queue(RmConst.QUEUE_TOPIC_USER);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindignUserExchangeMessages() {
        return BindingBuilder
                .bind(queueUserMessages())
                .to(topicExchange())
                .with("h.*.user");
    }
    // =======================以上是验证topic Excahnge============================

    // =======================以下是验证Fanout Excahnge============================
    @Bean
    public Queue aMessage(){
        return new Queue("h.fanout.A");
    }

    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange(RmConst.EXCHANGE_FANOUT);
    }

    @Bean
    public Binding bindingExchangeA(Queue aMessage,
                                    FanoutExchange fanoutExchange) {
        return BindingBuilder
                .bind(aMessage)
                .to(fanoutExchange);
    }
    // =======================以上是验证Fanout Excahnge============================
}

1.4 公共类

package com.h.rabbitmq.springboot.controller;

import com.h.rabbitmq.springboot.fanout.FanoutSender;
import com.h.rabbitmq.springboot.hello.DefaultSender;
import com.h.rabbitmq.springboot.topic.TopicSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 17:12
 */
@RestController
@RequestMapping("/rabbit")
public class RabbitTest {

    @Autowired
    private DefaultSender defaultSender;
    @Autowired
    private TopicSender topicSender;
    @Autowired
    private FanoutSender fanoutSender;


    /**普通测试类*/
    @GetMapping("/hello")
    public void hello() {
        defaultSender.send("hello message");
    }

    @GetMapping("/topicTest")
    public void topicTest() {
        topicSender.send();
    }

    @GetMapping("/fanoutTest")
    public void fanoutTest() {
        fanoutSender.send("hello fanout");
    }
}
package com.h.rabbitmq.springboot;

/**
 * @author h
 * @Description 常量类
 * @createTime 2020年06月25日 16:08
 */
public class RmConst {

    public static final String QUEUE_HELLO = "h.hello";
    public static final String QUEUE_USER = "h.user";

    public static final String EXCHANGE_TOPIC = "h.exchange";
    public static final String EXCHANGE_FANOUT = "h.fanout.exchange";

    public static final String QUEUE_TOPIC_EMAIL = "h.info.email";
    public static final String QUEUE_TOPIC_USER = "h.info.user";

    public static final String RK_EMAIL = "h.info.email";
    public static final String RK_USER = "h.info.user";
}

1.5 普通生产者 和 消费者

1.5.1 生产者

package com.h.rabbitmq.springboot.hello;

import com.h.rabbitmq.springboot.RmConst;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 生产者-发送消息
 * @createTime 2020年06月25日 16:55
 */
@Component
public class DefaultSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String message) {
        String sendMessage = message + "-----" + System.currentTimeMillis();
        System.out.println("sender : " + message);
        rabbitTemplate.convertAndSend(RmConst.QUEUE_HELLO, sendMessage);
        rabbitTemplate.convertAndSend(RmConst.QUEUE_USER, sendMessage);
    }
}

1.5.2 消费者

package com.h.rabbitmq.springboot.hello;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 消费者-hello
 * @createTime 2020年06月25日 17:00
 */
@Component
@RabbitListener(queues = "h.hello")
public class HelloReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("HelloReceiver:" + message);
    }
}

添加了发送方确认的消费者

package com.h.rabbitmq.springboot.hello;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 消费者-加入发送方确认
 * @createTime 2020年06月25日 17:02
 */
@Component
public class UserReceiver implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            String msg = new String(message.getBody());
            System.out.println("UserReceiver----> 接收到消息:" + msg);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),
                    false);
            System.out.println("UserReceiver----> 消息已消费");

        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                    false, true);
            System.out.println("UserReceiver>>>>>>拒绝消息,要求Mq重新派发");
            e.printStackTrace();
            throw e;
        }
    }
}

1.6 topic 交换器,生产者 和 消费者

1.6.1 生产者

package com.h.rabbitmq.springboot.topic;

import com.h.rabbitmq.springboot.RmConst;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 生产者-主题交换器
 * @createTime 2020年06月25日 20:18
 */
@Component
public class TopicSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send() {
        String msg1 = "I am email mesaage msg======";
        System.out.println("TopicSender send the 1st : " + msg1);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, RmConst.RK_EMAIL, msg1);

        String msg2 = "I am user mesaages msg########";
        System.out.println("TopicSender send the 2nd : " + msg2);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, RmConst.RK_USER, msg2);

        String msg3 = "I am error mesaages msg";
        System.out.println("TopicSender send the 3rd : " + msg3);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, "errorKey", msg3);
    }
}

1.6.2 消费者

package com.h.rabbitmq.springboot.topic;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 消费者-主题交换器
 * @createTime 2020年06月25日 20:18
 */
@Component
@RabbitListener(queues = "h.info.email")
public class TopicEmailMessageReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("TopicEmailMessageReceiver process: " + message);
    }
}
package com.h.rabbitmq.springboot.topic;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 20:28
 */
@Component
@RabbitListener(queues = "h.info.user")
public class TopicUserMessageReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("TopicUserMessageReceiver process: " + message);
    }
}

1.7 广播交换器,生产者 和 消费者

1.7.1 生产者

package com.h.rabbitmq.springboot.fanout;

import com.h.rabbitmq.springboot.RmConst;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 20:35
 */
@Component
public class FanoutSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String message) {
        String sendMsg = message +"---"+ System.currentTimeMillis();;
        System.out.println("FanoutSender : " + sendMsg);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_FANOUT, "", message);
    }
}

1.7.2 消费者

package com.h.rabbitmq.springboot.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 广播交换器
 *      队列的名称要与配置类 RabbitConfig 中声明的队列保持一致,否则启动会报错,找不到队列。
 * @createTime 2020年06月25日 20:42
 */
@Component
@RabbitListener(queues = "h.fanout.A")
public class FanoutReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("FanoutReceiver process: " + message);
    }
}

2、RabbitMQ 异步解耦实战

2.1 场景:

订单系统 与 库存系统之间添加 RabbitMQ,达到解耦效果,不过是哪个系统出现故障也不会影响到另一个系统的正常运行。

2.2 RPC 实现:

在这里插入图片描述

2.3 RabbitMQ 实现:

  • 发送方确认、失败者通知(确保消息能够到MQ)
  • 消息持久化(交换器、队列、消息 都需要持久化)
  • 确保消息一定能够被存库消费,手动应答
    * RabbitMQ 集成springboot 与 异步解耦实战_第1张图片

2.4 具体代码

2.4.1 生产者服务:

添加 maven 依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!--springboot集成rabbitmq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置 rabbit 连接参数

server.port=8080
spring.application.name=springboot-rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
# 发送方确认
spring.rabbitmq.publisher-confirms=true
# 虚拟主机
spring.rabbitmq.virtual-host=/

配置类:

package com.h.rabbitmq.springboot.config;

import com.h.rabbitmq.springboot.RmConst;
import com.h.rabbitmq.springboot.hello.UserReceiver;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 15:10
 */
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.host}")
    private String addresses;
    @Value("${spring.rabbitmq.port}")
    private String port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;
    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms;

    @Autowired
    private UserReceiver userReceiver;


    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(addresses + ":" + port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        // 如果要进行消息回调,则这里必须要设置为true
        connectionFactory.setPublisherConfirms(publisherConfirms);

        return connectionFactory;
    }

    /**rabbitAdmin 类封装对RabbitMQ的管理操作*/
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public RabbitTemplate newRabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        // 开启生产者确认
        rabbitTemplate.setMandatory(true);
        // 发送方确认
        rabbitTemplate.setConfirmCallback(confirmCallback());
        // 失败回调
        rabbitTemplate.setReturnCallback(returnCallback());
        return rabbitTemplate;
    }

    /**生产者失败通知(无法路由)*/
    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return new RabbitTemplate.ReturnCallback(){
            @Override
            public void returnedMessage(Message message,
                                        int replyCode,
                                        String replyText,
                                        String exchange,
                                        String routingKey) {
                System.out.println("无法路由的消息,需要考虑另外处理。");
                System.out.println("Returned replyText:" + replyText);
                System.out.println("Returned exchange:" + exchange);
                System.out.println("Returned routingKey:" + routingKey);
                System.out.println("Returned Message:" + new String(message.getBody()));
            }
        };
    }

    /**生产者发送确认*/
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData,
                                boolean ack,
                                String cause) {
                if (ack) {
                    System.out.println("发送者确认发送mq成功");
                } else {
                    System.out.println("发送者发送给mq失败,考虑重发:" + cause);
                }
            }
        };
    }

    // =======================以下是验证topic Excahnge============================
    /**申明交换器*/
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(RmConst.EXCHANGE_TOPIC);
    }

    @Bean
    public Queue queueEmailMessage() {
        return new Queue(RmConst.QUEUE_TOPIC_EMAIL);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindingEmailExchangeMessage() {
        return BindingBuilder
                .bind(queueEmailMessage())
                .to(topicExchange())
                .with("h.*.email");
    }

    @Bean
    public Queue queueUserMessages() {
        return new Queue(RmConst.QUEUE_TOPIC_USER);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindignUserExchangeMessages() {
        return BindingBuilder
                .bind(queueUserMessages())
                .to(topicExchange())
                .with("h.*.user");
    }
    // =======================以上是验证topic Excahnge============================

}

生产者(主题交换器)

package com.h.rabbitmq.springboot.topic;

import com.h.rabbitmq.springboot.RmConst;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 生产者-主题交换器
 * @createTime 2020年06月25日 20:18
 */
@Component
public class TopicSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send() {
        String msg1 = "I am email mesaage msg======";
        System.out.println("TopicSender send the 1st : " + msg1);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, RmConst.RK_EMAIL, msg1);

        String msg2 = "I am user mesaages msg########";
        System.out.println("TopicSender send the 2nd : " + msg2);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, RmConst.RK_USER, msg2);

        String msg3 = "I am error mesaages msg";
        System.out.println("TopicSender send the 3rd : " + msg3);
        rabbitTemplate.convertAndSend(RmConst.EXCHANGE_TOPIC, "errorKey", msg3);
    }
}

生产者-控制层

package com.h.rabbitmq.springboot.controller;

import com.h.rabbitmq.springboot.fanout.FanoutSender;
import com.h.rabbitmq.springboot.hello.DefaultSender;
import com.h.rabbitmq.springboot.topic.TopicSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 17:12
 */
@RestController
@RequestMapping("/rabbit")
public class RabbitTest {

    @Autowired
    private DefaultSender defaultSender;
    @Autowired
    private TopicSender topicSender;
    @Autowired
    private FanoutSender fanoutSender;

    @GetMapping("/topicTest")
    public void topicTest() {
        topicSender.send();
    }
    
}

2.4.2 消费者服务:

添加 maven 依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<!--springboot集成rabbitmq-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

配置 rabbit 连接参数

server.port=8080
spring.application.name=springboot-rabbitmq-consumer
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
# 发送方确认
spring.rabbitmq.publisher-confirms=true
# 虚拟主机
spring.rabbitmq.virtual-host=/

常量类:

package com.h.rabbitsync;

/**
 * @author h
 * @Description 常量类
 * @createTime 2020年06月25日 16:08
 */
public class RmConst {
    public static final String EXCHANGE_TOPIC = "h.exchange";

    public static final String QUEUE_TOPIC_EMAIL = "h.info.email";
    public static final String QUEUE_TOPIC_USER = "h.info.user";
}

配置类:

package com.h.rabbitsync.config;

import com.h.rabbitsync.RmConst;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 15:10
 */
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.host}")
    private String addresses;
    @Value("${spring.rabbitmq.port}")
    private String port;
    @Value("${spring.rabbitmq.username}")
    private String username;
    @Value("${spring.rabbitmq.password}")
    private String password;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;
    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(addresses + ":" + port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        // 如果要进行消息回调,则这里必须要设置为true
        connectionFactory.setPublisherConfirms(publisherConfirms);

        return connectionFactory;
    }

    /**rabbitAdmin 类封装对RabbitMQ的管理操作*/
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public RabbitTemplate newRabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
        // 开启生产者确认
        rabbitTemplate.setMandatory(true);
        // 发送方确认
        rabbitTemplate.setConfirmCallback(confirmCallback());
        // 失败回调
        rabbitTemplate.setReturnCallback(returnCallback());
        return rabbitTemplate;
    }

    /**生产者失败通知(无法路由)*/
    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return new RabbitTemplate.ReturnCallback(){
            @Override
            public void returnedMessage(Message message,
                                        int replyCode,
                                        String replyText,
                                        String exchange,
                                        String routingKey) {
                System.out.println("无法路由的消息,需要考虑另外处理。");
                System.out.println("Returned replyText:" + replyText);
                System.out.println("Returned exchange:" + exchange);
                System.out.println("Returned routingKey:" + routingKey);
                System.out.println("Returned Message:" + new String(message.getBody()));
            }
        };
    }

    /**生产者发送确认*/
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData,
                                boolean ack,
                                String cause) {
                if (ack) {
                    System.out.println("发送者确认发送mq成功");
                } else {
                    System.out.println("发送者发送给mq失败,考虑重发:" + cause);
                }
            }
        };
    }

    // =======================以下是验证topic Excahnge============================
    /**申明交换器*/
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(RmConst.EXCHANGE_TOPIC);
    }

    @Bean
    public Queue queueEmailMessage() {
        return new Queue(RmConst.QUEUE_TOPIC_EMAIL);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindingEmailExchangeMessage() {
        return BindingBuilder
                .bind(queueEmailMessage())
                .to(topicExchange())
                .with("h.*.email");
    }

    @Bean
    public Queue queueUserMessages() {
        return new Queue(RmConst.QUEUE_TOPIC_USER);
    }

    /**建立绑定关系*/
    @Bean
    public Binding bindignUserExchangeMessages() {
        return BindingBuilder
                .bind(queueUserMessages())
                .to(topicExchange())
                .with("h.*.user");
    }
    // =======================以上是验证topic Excahnge============================
}

消费者一:

package com.h.rabbitsync.service;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description TODO
 * @createTime 2020年06月25日 20:28
 */
@Component
@RabbitListener(queues = "h.info.user")
public class TopicUserMessageReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("TopicUserMessageReceiver process: " + message);
    }
}

消费者二:

package com.h.rabbitsync.service;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author h
 * @Description 消费者-主题交换器
 * @createTime 2020年06月25日 20:18
 */
@Component
@RabbitListener(queues = "h.info.email")
public class TopicEmailMessageReceiver {

    @RabbitHandler
    public void process(String message) {
        System.out.println("TopicEmailMessageReceiver process: " + message);
    }
}

你可能感兴趣的:(消息中间件)