Spring Boot 2.x 集成 RabbitMQ

一、新建springboot项目,使用目前最新版本 2.1.3.RELEASE

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.1.3.RELEASE</version>
</parent>

<dependencies>

    <!--AMQP starter-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>

    <!--jackson-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

    <!--测试-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

</dependencies>

二、编写application.properties文件

spring.application.name=rabbitmq-demo
server.port=8080

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.publisher-returns=true

# 开启ACK
spring.rabbitmq.listener.direct.acknowledge-mode=manual
spring.rabbitmq.listener.simple.acknowledge-mode=manual

三、RabbitMQ配置类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author zhengqiang.shi
 * @Date 2019-03-19 16:15
 */
@Configuration
public class RabbitConfig implements InitializingBean {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @Description: 配置MessageConverter,会自动设置到RabbitTemplate
     * @see org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
     * @Param: []
     * @return: org.springframework.amqp.support.converter.MessageConverter
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * @Description: 配置消息发布确认、失败退回
     * 需要在application.properties中显式开启
     *      spring.rabbitmq.publisher-confirms=true
     *      spring.rabbitmq.publisher-returns=true
     * @Param: []
     * @return: void
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        rabbitTemplate.setReturnCallback((message, replyCode, replyText,exchange,routingKey) -> {
            logger.error("message:{}, replyCode:{} replyText:{} exchange: {}  routingKey: {}", message, replyCode, replyText, exchange, routingKey);
        });

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(ack){
                logger.info("发送成功");
            } else {
                logger.error("发送失败,msg:{}",cause);
            }
        });
    }
}

注:消息传输需要序列化,默认实现为SimpleMessageConverter,此处配置为Jackson2JsonMessageConverter,原因为SimpleMessageConverter 对于要发送的消息体 body 为 byte[] 时不进行处理,如果是 String 则转成字节数组,如果是 Java 对象,则使用 jdk 序列化将消息转成字节数组,转出来的结果较大,含class类名,类相应方法等信息。因此性能较差。

四、发送消息-fanout

  • 4.1、FanoutRabbitConfig(配置fanout类型的队列、交换器、绑定)
package com.learn.fanout;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author zhengqiang.shi
 * @Date 2019-03-19 17:45
 */
@Configuration
public class FanoutRabbitConfig {

    /**
     * @Description: 定义队列A
     * @Param: []
     * @return: org.springframework.amqp.core.Queue
     */
    @Bean
    public Queue queueA(){
        return new Queue(FanoutConstant.QUEUE_NAME_A);
    }

    /**
     * @Description: 定义队列B
     * @Param: []
     * @return: org.springframework.amqp.core.Queue
     */
    @Bean
    public Queue queueB(){
        return new Queue(FanoutConstant.QUEUE_NAME_B);
    }
    
    /**
     * @Description: 定义fanout类型的交换器
     * @Param: []
     * @return: org.springframework.amqp.core.FanoutExchange
     */
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(FanoutConstant.EXCHANGE_NAME);
    }

    /**
     * @Description: 绑定队列A
     * @Param: [queueA, fanoutExchange]
     * @return: org.springframework.amqp.core.Binding
     */
    @Bean
    public Binding bindingQueueA(Queue queueA,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(queueA).to(fanoutExchange);
    }

    /**
     * @Description: 绑定队列B
     * @Param: [queueB, fanoutExchange]
     * @return: org.springframework.amqp.core.Binding
     */
    @Bean
    public Binding bindingQueueB(Queue queueB,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(queueB).to(fanoutExchange);
    }
}
  • 4.2FanoutConstant(相关常量)
package com.learn.fanout;

/**
 * @Author zhengqiang.shi
 * @Date 2019-03-19 17:50
 */
public class FanoutConstant {

    public static final String EXCHANGE_NAME = "com.msg.fanout";

    public static final String QUEUE_NAME_A = "queue.A";
    public static final String QUEUE_NAME_B = "queue.B";
}
  • 4.3、FanoutReceiver 监听消息
package com.learn.fanout;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author zhengqiang.shi
 * @Date 2019-03-19 17:56
 */
@Component
public class FanoutReceiver {

    @RabbitListener(queues = FanoutConstant.QUEUE_NAME_A)
    public void receiveQueueA(String msg, Channel channel, Message message){
        System.out.println("queueA receive:"+msg);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues = FanoutConstant.QUEUE_NAME_B)
    public void receiveQueueB(String msg,Channel channel, Message message){
        System.out.println("queueB receive:"+msg);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
  • 4.4、测试类-sendByFanout()
import com.learn.DemoApplication;
import com.learn.fanout.FanoutConstant;
import com.learn.model.User;
import com.learn.topic.TopicConstant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author zhengqiang.shi
 * @Date 2019-03-19 17:57
 */
@SpringBootTest(classes = DemoApplication.class)
@RunWith(SpringRunner.class)
public class TestRabbitMQ {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void sendByFanout() {
        String msg = "hello " + LocalDateTime.now();
        // fanout类型的交换器,会把所有发送到该交换器的消息路由到所有与该交换器绑定的队列中,所以不用指定routingKey
        rabbitTemplate.convertAndSend(FanoutConstant.EXCHANGE_NAME, "", msg);
    }

}
  • 4.5、测试结果

queueA receive:hello 2019-03-19T18:08:17.598
queueB receive:hello 2019-03-19T18:08:17.598

 # 其他类型direct、topic主要匹配routingKey,写法大同小异,此处不再举例

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值