zoukankan      html  css  js  c++  java
  • spring boot 2.0+ 整合RabbitMq

    1、添加包

    1 <dependency>
    2       <groupId>org.springframework.boot</groupId>
    3      <artifactId>spring-boot-starter-amqp</artifactId>
    4 </dependency>

    2、配置文件

    pring:
    # 消息队列
    rabbitmq:
    username: admin
    password: admin
    port: 5672
    host: 192.168.1.118
    listener:
    simple:
    acknowledge-mode: manual

    3、生产者,其中MSGRABBITQUERENAME为队列名称

     1 @Component
     2 public class RabbitProducer {
     3 
     4     @Autowired
     5     AmqpTemplate rabbitTemplate;
     6 
     7     static final String MSGRABBITQUERENAME="chat.send.msg";
     8 
     9     public void sendMessages(String str) {
    10         this.rabbitTemplate.convertAndSend(MSGRABBITQUERENAME,str);
    11     }
    12 }

    4、消费者,我这里为手动确认模式,确保数据有效性。

    @Component
    public class RabbitListener {
    
        @org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "leenleda.test")
        public void onMessage(@Payload String msg,
                              @Headers Map<String, Object> headers,
                              Channel channel) throws Exception{
            try {
                //消息确认,(deliveryTag,multiple是否确认所有消息)
                channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);
            } catch (Exception e) {
                //消息拒绝(deliveryTag,multiple,requeue拒绝后是否重新回到队列)
                channel.basicNack((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false, true);
                // 拒绝一条
                // channel.basicReject();
            }
        }
    }

    然后直接调用就可以了

  • 相关阅读:
    JavaScript等比例缩放图片
    乐器的研究
    乐器的研究
    单位的理解
    单位的理解
    那些狗,那些人
    Opencv+Zbar二维码识别(标准条形码/二维码识别)
    二维码解码器Zbar+VS2012开发环境配置
    条形码、二维码的区别和组成结构介绍
    Caffe-Windows下遇到过的问题、技巧、解决方案
  • 原文地址:https://www.cnblogs.com/rolayblog/p/11248508.html
Copyright © 2011-2022 走看看