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();
            }
        }
    }

    然后直接调用就可以了

  • 相关阅读:
    调试脚本
    if [ $? -eq 0 ]的含义
    主键和索引的区别
    Docker守护式容器
    Docker容器的基本操作
    Linux下Docker的安装
    Linux下查看占用CPU资源最多的几个进程
    报错:pymysql.err.InternalError: (1054, "Unknown column 'AType' in 'field list'")
    在webpack中使用postcss-px2rem的
    vue环境配置脚手架环境搭建vue工程目录
  • 原文地址:https://www.cnblogs.com/rolayblog/p/11248508.html
Copyright © 2011-2022 走看看