Java Code Examples for com.rabbitmq.client.Channel#basicNack()

The following examples show how to use com.rabbitmq.client.Channel#basicNack() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyAckReceiver.java    From springboot-learn with MIT License 6 votes vote down vote up
@RabbitHandler
public void process(String sendMsg, Channel channel, Message message) {

    System.out.println("AckReceiver  : 收到发送消息 " + sendMsg + ",收到消息时间"
            + LocalDateTime.now(ZoneId.systemDefault()));

    try {
        //告诉服务器收到这条消息已经被当前消费者消费了,可以在队列安全删除,这样后面就不会再重发了,
        //否则消息服务器以为这条消息没处理掉,后续还会再发
        //第二个参数是消息的标识,false只确认当前一个消息收到,true确认所有consumer获得的消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        System.out.println("process success");
    } catch (Exception e) {
        System.out.println("process fail");
        try {
            //ack返回false,并重新回到队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }

}
 
Example 2
Source File: ReceiveService.java    From seed with Apache License 2.0 6 votes vote down vote up
@RabbitListener(queues="${spring.rabbitmq.queues}", containerFactory="jadyerRabbitListenerContainerFactory")
public void receive(UserMsg userMsg, Channel channel, Message message){
    try {
        LogUtil.getLogger().info("收到消息-->[{}]", ReflectionToStringBuilder.toString(userMsg));
        //确认消费成功(第一个参数:消息编号。第二个参数:是否确认多条消息,false为确认当前消息,true为确认deliveryTag编号以前的所有消息)
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }catch(Exception e){
        LogUtil.getLogger().error("消息处理异常,消息ID={}, 消息体=[{}]", message.getMessageProperties().getCorrelationId(), JSON.toJSONString(userMsg), e);
        try {
            //拒绝当前消息,并把消息返回原队列(第三个参数:是否将消息放回队列,true表示放回队列,false表示丢弃消息)
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            //basicReject只能拒绝一条消息,而basicNack能够拒绝多条消息
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e1) {
            LogUtil.getLogger().error("消息basicNack时发生异常,消息ID={}", message.getMessageProperties().getCorrelationId(), e);
        }
    }
}
 
Example 3
Source File: MQAwareListener.java    From lemon-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Override
  public void onMessage(Message message, Channel channel) throws IOException {
      System.out.println("----- received" + message.getMessageProperties());
try {
	Object msg = messageConverter.fromMessage(message);
	if (!appId.equals(message.getMessageProperties().getAppId())){
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        throw new SecurityException("非法应用appId:" + message.getMessageProperties().getAppId());
	}
	Object service = ctx.getBean(message.getMessageProperties().getHeaders().get("ServiceName").toString());
	String serviceMethodName = message.getMessageProperties().getHeaders().get("ServiceMethodName").toString();
	Method method = service.getClass().getMethod(serviceMethodName, msg.getClass());
       method.invoke(service, msg);
       //确认消息成功消费
       channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
	System.out.println("------ err"+ e.getMessage());
       channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
  }
 
Example 4
Source File: Receiver.java    From easy-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message message, Channel channel) throws Exception {
  try {
    MessageProperties prop = message.getMessageProperties();
    ConsumerDef consumer = ConsumerDef.lookup(prop.getConsumerQueue(), prop.getReceivedExchange(),
        prop.getReceivedRoutingKey());
    if (consumer == null) {
      log.error("consumer not found {}", prop);
      channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
      return;
    }
    Object msg = converter.fromMessage(message);
    if (converter instanceof CustomMessageConverter && msg instanceof byte[]) {
      // 特殊处理
      Type type = consumer.getType();
      if (type != byte[].class) {
        msg = JSON.parseObject((byte[]) msg, type);
      }
    }
    if (log.isDebugEnabled()) {
      log.debug("receive msg {}", msg);
    }
    consumer.accept(msg);
    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
  } catch (Exception e) {
    log.error("receive msg error {}", message, e);
    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
  }
}
 
Example 5
Source File: LocalListner.java    From cloud-espm-cloud-native with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to process messages from queue.
 * 
 * @param in
 * @param channel
 * @param tag
 * @throws IOException
 * @throws InterruptedException
 */
@RabbitListener(queues = "espm.salesOrders")
public void recieve(SalesOrder in, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
		throws IOException, InterruptedException {

	SalesOrderRepository repo = appContext.getBean(SalesOrderRepository.class);
	try {
		if (!repo.existsById(in.getSalesOrderId())) {
			repo.save(in);
			logger.info(in.getSalesOrderId() + " created");
			channel.basicAck(tag, false);
			value = initialValue;

		} else {
			logger.error(in.getSalesOrderId() + " already Exists, Deleting from Queue");
			channel.basicAck(tag, false);

		}
	} catch (DataIntegrityViolationException e) {
		logger.error(in.getSalesOrderId() + " is an invalid Sales-Order, Deleting from Queue");
		channel.basicNack(tag, false, false);

	} catch (CannotCreateTransactionException ccte) {
		logger.error("Unable to connect to DB");
		logger.error("Backing  for " + value);
		TimeUnit.MILLISECONDS.sleep(value);
		if (value <= maxVal)
			value = value * multiplier;
		channel.basicNack(tag, false, true);

	}

}
 
Example 6
Source File: AbstractMqListener.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@RabbitHandler
@Override
public void process(T obj, Message message, Channel channel) throws Exception {
    // 确认消息
    this.basicAck(channel, message.getMessageProperties().getDeliveryTag());

    if (!this.doProcess(obj, message, channel)) {
        log.error("消息确认失败未消费");
        // 处理业务发生异常,不消费消息,可重新再次消费消息
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
    }
}
 
Example 7
Source File: AbstractMqListener.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Override
public void basicAck(Channel channel, long deliveryTag) {
    try {
        log.info("消息确认成功已消费");
        channel.basicAck(deliveryTag, false);
    } catch (IOException e) {
        log.error("消息确认失败未消费");
        try {
            // 重新接收消息,不消费此消息
            channel.basicNack(deliveryTag, false, true);
        } catch (IOException e1) {
            log.error("重新发送消息失败。。。");
        }
    }
}
 
Example 8
Source File: ProducerConsumer.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void consumer1() throws Exception {
		//1、获取连接
        Connection connection =RabbitMqConnectionFactoy.getConnection();
        //2、声明通道
        Channel channel = connection.createChannel();
        //3、声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了)
        channel.basicQos(1);//每次处理1个
        //4、定义队列的消费者
        //定义消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                    throws IOException {
                //获取并转成String
                String message = new String(body, "UTF-8");
                System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString());
                /**
                 *     basicAck:成功消费,消息从队列中删除 
					   basicNack:requeue=true,消息重新进入队列,false被删除 
					   basicReject:等同于basicNack 
					   basicRecover:消息重入队列,requeue=true,发送给新的consumer,false发送给相同的consumer 
                 */
//                channel.basicAck(envelope.getDeliveryTag(), false);
//                channel.basicReject(envelope.getDeliveryTag(), false);//拒绝此条消息,并重发到队列(可能再次受到此消息)
//                channel.basicRecover(true);//消息重发给其它消费者
                channel.basicNack(envelope.getDeliveryTag(), false, false);
            }
        };
        channel.basicConsume(QUEUE_NAME, autoAck,consumer);
	}
 
Example 9
Source File: MessageAdapterHandler.java    From shine-mq with Apache License 2.0 4 votes vote down vote up
@Override
public void onMessage(Message message, Channel channel) throws Exception {
    EventMessage em = null;
    Coordinator coordinator = null;
    long tag = message.getMessageProperties().getDeliveryTag();
    String msgId = message.getMessageProperties().getMessageId();
    try {
        ProcessorWrap wrap;
        em = JSON.parseObject(message.getBody(), EventMessage.class);
        if (MqConstant.DEAD_LETTER_EXCHANGE.equals(message.getMessageProperties().getReceivedExchange()) &&
                MqConstant.DEAD_LETTER_ROUTEKEY.equals(message.getMessageProperties().getReceivedRoutingKey())) {
            wrap = map.get(MqConstant.DEAD_LETTER_EXCHANGE + "_" + MqConstant.DEAD_LETTER_ROUTEKEY +
                    "_" + SendTypeEnum.DLX);
        } else {
            wrap = map.get(em.getExchangeName() + "_" + em.getRoutingKey() + "_" + em.getSendTypeEnum());
        }
        //如果是分布式事务的消息,sdk提供ack应答,无须自己手动ack
        if (SendTypeEnum.DISTRIBUTED.toString().equals(em.getSendTypeEnum())) {
            Objects.requireNonNull(em.getCoordinator(),
                    "Distributed transaction message error: coordinator is null.");
            coordinator = (Coordinator) applicationContext.getBean(em.getCoordinator());
            wrap.process(em.getData(), message, channel);
            channel.basicAck(tag, false);
        } else {
            wrap.process(em.getData(), message, channel);
        }
    } catch (Exception e) {
        log.error("MessageAdapterHandler error, message: {} :", em, e);
        if (em != null && coordinator != null && SendTypeEnum.DISTRIBUTED.toString().equals(em.getSendTypeEnum())) {
            Double resendCount = coordinator.incrementResendKey(MqConstant.RECEIVE_RETRIES, msgId);
            if (resendCount >= rabbitmqFactory.getConfig().getDistributed().getReceiveMaxRetries()) {
                if (Strings.isNullOrEmpty(em.getRollback())) {
                    // 放入死信队列
                    channel.basicNack(tag, false, false);
                } else {
                    em.setSendTypeEnum(SendTypeEnum.ROLLBACK.toString());
                    em.setRoutingKey(em.getRollback());
                    rabbitmqFactory.setCorrelationData(msgId, em.getCoordinator(), em,
                            null);
                    coordinator.setRollback(msgId, em);
                    rabbitmqFactory.getTemplate().send(em, 0, 0, SendTypeEnum.ROLLBACK);
                    channel.basicAck(tag, false);
                }
                coordinator.delResendKey(MqConstant.RECEIVE_RETRIES, msgId);
            } else {
                // 重新放入队列 等待消费
                channel.basicNack(tag, false, true);
            }
        } else {
            throw e;
        }
    }
}