SpringBoot2x整合RabbitMQ

导读:本篇文章讲解 SpringBoot2x整合RabbitMQ,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

        SpringBoot2x整合RabbitMQ,消息队列有很多优秀的中间件,但是我比较喜欢而且项目中实际用到过并且比较好用的就是RabbitMQ,下面是整合过程。

        1、xml

  # RabbitMQ 配置
  rabbitmq:
    host: xxx.xxx.xxx.xxx
    port: 5672
    username: xxxx
    password: xxxx
    virtual-host: /
    listener:
      simple:
        prefetch: 1

        2、pom

        <!-- rabbitmq 配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        3、config(配置成功后启动程序,自动创建交换机和队列)

@Configuration
public class RabbitMqConfig {

    @Bean
    DirectExchange exchange() {
        // EXCHANGE 交换机,自己配置
        return new DirectExchange(CommonConstants.EXCHANGE);
    }

    @Bean
    Queue sendMsgQueue() {
        Map<String, Object> map = new HashMap<>();
        map.put("x-max-priority", 40);
        // UNTREATED_MSG_QUEUE 消息队列名称
        return new Queue(CommonConstants.UNTREATED_MSG_QUEUE, true, false, false, map);
    }

    @Bean
    public Binding bindingSendMsg() {
        return BindingBuilder.bind(sendMsgQueue()).to(exchange()).with(CommonConstants.UNTREATED_MSG_QUEUE);
    }


}

        4、发送消息

@Component
@RequiredArgsConstructor
public class SendMsgHandle {

    private static Logger logger = LoggerFactory.getLogger(SendMsgHandle.class);

    private final AmqpTemplate amqpTemplate;

    public void send(String queue,String msg) {
        logger.info("向队列:{},发送消息:{}",queue,msg);
        try {
            amqpTemplate.convertAndSend(queue, msg);
        } catch (AmqpException e) {
            logger.error("向队列:{},发送消息:{},出现异常",queue,msg,e.getMessage(),e);
        }
    }

}

        5、接收消息

@Component
public class ReceiveMsgHandle {

    private static Logger logger = LoggerFactory.getLogger(ReceiveMsgHandle.class);

    // PROCESSED_MSG_QUEUE 监听的消息队列
    @RabbitListener(queues = {CommonConstants.PROCESSED_MSG_QUEUE}, concurrency = "1")
    public void processedQueue(String content, Message message, Channel channel) {
        try {
            // 接收到的消息可以转化成对象之后进行处理
            /*SendMsgVO msg = JSON.parseObject(content, SendMsgVO.class);*/
            logger.info("接收到消息==> content:{},message :{},channel:{}",content, message, channel);
        }catch (Exception e){
            logger.info(e.getMessage());
        }finally {
            return;
        }
    }

}

        6、集成测试

    @ApiOperation(value = "RabbitMQ集成测试" , notes = "RabbitMQ集成测试")
    @GetMapping("/rabbitMqTest")
    public Result rabbitMqTest(){
        sendMsgHandle.send(CommonConstants.PROCESSED_MSG_QUEUE,"RabbitMQ集成测试");
        return Result.ok();
    }

        7、综上,集成完毕,可以使用MQ了。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101712.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!