當前位置: 首頁>>代碼示例>>Java>>正文


Java Channel.basicAck方法代碼示例

本文整理匯總了Java中com.rabbitmq.client.Channel.basicAck方法的典型用法代碼示例。如果您正苦於以下問題:Java Channel.basicAck方法的具體用法?Java Channel.basicAck怎麽用?Java Channel.basicAck使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.rabbitmq.client.Channel的用法示例。


在下文中一共展示了Channel.basicAck方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicQos(1);
	channel.basicConsume("trade.eq.q", false, consumer);

	int numMsgs = args.length > 0 ? new Integer(args[0]).intValue() : 1;
	for (int i=0; i<numMsgs; i++) {
		QueueingConsumer.Delivery msg = consumer.nextDelivery();
		System.out.println("message received: " + new String(msg.getBody()));
		Thread.sleep(1000);
		channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
	}			
	
	AMQPCommon.close(channel);
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:17,代碼來源:AMQPReceiver.java

示例2: onMessage

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
/**
 * 普通消息監聽
 * 
 * @param message 消息實體
 * @param channel channel 就是當前的會話通道
 * @throws Exception 備注: 手動ack就是在當前channel裏麵調用basicAsk的方法,並傳入當前消息的tagId就可以了。
 */
@Override
public void onMessage(Message message, Channel channel) throws Exception {
	long deliveryTag = message.getMessageProperties().getDeliveryTag();
	logger.debug("deliveryTag= " + deliveryTag);
	try {
		logger.info("------消費者處理消息------");
		logger.info("receive message" + message.getMessageProperties().getAppId());
		logger.info("receive channel" + channel.getChannelNumber() + "----");
		// 獲取消息
		if (null != message.getBody()) {
			EventMessage eventMessage = (EventMessage) ObjectAndByteCovertUtil.ByteToObject(message.getBody());
			if (null != eventMessage) {
				System.out.println(Thread.currentThread().getName() + ":" +  TimeUtils.getSysTime("yyyy-MM-dd HH:mm:ss") + ":[下遊應用- 消費普通消息]:" + message.getMessageProperties());
				// TODO 業務處理
			}
		}
		// 消息的標識,false隻確認當前一個消息收到,true確認所有consumer獲得的消息(成功消費,消息從隊列中刪除 )
		channel.basicAck(deliveryTag, false);
	} catch (Exception e) {
		logger.warn("message consume failed: " + e.getMessage());
		// ack返回false,requeue-true並重新回到隊列
		channel.basicNack(deliveryTag, false, true);
	}
}
 
開發者ID:butter-fly,項目名稱:belling-spring-rabbitmq,代碼行數:32,代碼來源:NormalMessageConsumer.java

示例3: onMessage

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
/**
 * 延遲消息監聽並處理
 * 
 * @param message 消息實體
 * @param channel channel 就是當前的會話通道
 * @throws Exception 備注: 手動ack就是在當前channel裏麵調用basicAsk的方法,並傳入當前消息的tagId就可以了。
 */
@Override
public void onMessage(Message message, Channel channel) throws Exception {
	long deliveryTag = message.getMessageProperties().getDeliveryTag();
	logger.debug("deliveryTag= " + deliveryTag);
	try {
		
		logger.info("[延時消息]" + message.getMessageProperties());
		// 獲取消息
		if (null != message.getBody()) {
			EventMessage eventMessage = (EventMessage) ObjectAndByteCovertUtil.ByteToObject(message.getBody());
			if (null != eventMessage) {
				System.out.println(Thread.currentThread().getName() + ":" + TimeUtils.getSysTime("yyyy-MM-dd HH:mm:ss") + ":[下遊應用-消費延時消息]:" + eventMessage.getObject().toString());
				// TODO 業務處理
			}
		}
		// 手動確認 - false隻確認當前一個消息收到,true確認所有consumer獲得的消息
		channel.basicAck(deliveryTag, false);
	} catch (Exception e) {
		logger.warn("message consume failed: " + e.getMessage());
		// ack返回false,requeue-true並重新回到隊列
		channel.basicNack(deliveryTag, false, true);
	}
}
 
開發者ID:butter-fly,項目名稱:belling-spring-rabbitmq,代碼行數:31,代碼來源:DelayMessageConsumer.java

示例4: onMessage

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
@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);
}
  }
 
開發者ID:lemon-china,項目名稱:lemon-rabbitmq,代碼行數:21,代碼來源:MQAwareListener.java

示例5: start

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public void start(Connection connection) {
	try {
		active = true;
		Channel channel = connection.createChannel();
		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicQos(1);
		channel.basicConsume("trade.eq.q", false, consumer);
		while (active) {
			QueueingConsumer.Delivery msg = consumer.nextDelivery();
			System.out.println("message received: " + new String(msg.getBody()));
			Thread.sleep(1000);
			channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
		}
		channel.close();
	} catch (Exception e) {
		e.printStackTrace();
	}	
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:19,代碼來源:AMQPConsumer.java

示例6: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
/**
 * @param args
 * @throws TimeoutException
 * @throws IOException
 * @throws InterruptedException
 * @throws ConsumerCancelledException
 * @throws ShutdownSignalException
 */
public static void main(String[] args) throws IOException, TimeoutException, ShutdownSignalException,
		ConsumerCancelledException, InterruptedException {
	ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(host);
	factory.setUsername(username);
	factory.setPassword(password);
	factory.setPort(port);
	factory.setVirtualHost(virtualHost);
	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();
	channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
	channel.basicQos(1);
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

	System.out.println("RPCServer Awating RPC request");
	while (true) {
		QueueingConsumer.Delivery delivery = consumer.nextDelivery();
		BasicProperties props = delivery.getProperties();
		BasicProperties replyProps = new AMQP.BasicProperties.Builder().correlationId(props.getCorrelationId())
				.build();

		String message = new String(delivery.getBody(), "UTF-8");
		int n = Integer.parseInt(message);

		System.out.println("RPCServer fib(" + message + ")");
		String response = "" + fib(n);
		channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());
		channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
	}
}
 
開發者ID:pudoj,項目名稱:june.mq,代碼行數:40,代碼來源:RPCServer.java

示例7: dispatchMessages

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public void dispatchMessages() throws Exception {
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicQos(1);
	channel.basicConsume("trade.eq.q", false, consumer);

	while (true) {
		QueueingConsumer.Delivery msg = consumer.nextDelivery();
		channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
		new Thread(new POJOThreadProcessor(
			this, new String(msg.getBody()))).start();
		numThreads++;
		System.out.println("Threads: " + numThreads);
	}			
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:16,代碼來源:AMQPThreadDispatcher.java

示例8: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicQos(1);
	channel.basicConsume("trade.eq.q", false, consumer);

	while (true) {
		QueueingConsumer.Delivery msg = consumer.nextDelivery();
		Thread.sleep(2000);
		System.out.println("Trade placed: " + new String(msg.getBody()));
		channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
	}			
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:14,代碼來源:AMQPThreadConsumer.java

示例9: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicQos(1);
	channel.basicConsume("trade.eq.q", false, consumer);

	while (true) {
		QueueingConsumer.Delivery msg = consumer.nextDelivery();
		System.out.println("message received: " + new String(msg.getBody()));
		Thread.sleep(2000);
		channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
	}			
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:14,代碼來源:AMQPContConsumer.java

示例10: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
	Channel channel = AMQPCommon.connect();
	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicQos(1);
	channel.basicConsume(args[0], false, consumer);

	while (true) {
		QueueingConsumer.Delivery msg = consumer.nextDelivery(1000);
		if (msg == null) break;
		System.out.println("message received: " + new String(msg.getBody()));
		Thread.sleep(100);
		channel.basicAck(msg.getEnvelope().getDeliveryTag(), false);
	}
	
	System.exit(0);
}
 
開發者ID:wmr513,項目名稱:reactive,代碼行數:17,代碼來源:AMQPSplitConsumer.java

示例11: ackAction

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
private Consumer<Void> ackAction(final long deliveryTag) {
    if (options.autoAckEnabled()) {
        return it -> {};
    }
    return it -> {
        final Channel channel = getChannel();
        try {
            channel.basicAck(deliveryTag, false);
        } catch (final IOException e) {
            throw new IllegalStateException(String.format("Could not deliver ack for: %d", deliveryTag), e);
        }
    };
}
 
開發者ID:FinderSystems,項目名稱:Elmer,代碼行數:14,代碼來源:InternalConsumer.java

示例12: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:[email protected]");
    factory.setConnectionTimeout(300000);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare("my-queue", true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("my-queue", false, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        if (delivery != null) {
            try {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("Message consumed: " + message);
                // Interact with IO
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception e) {
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), true);
            }
        }
    }

}
 
開發者ID:nyholmniklas,項目名稱:rabbitmq-tutorial,代碼行數:28,代碼來源:Consumer.java

示例13: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
/**
 * @param args
 * @throws IOException
 * @throws TimeoutException
 * @date 2017年7月11日 下午5:55:38
 * @writer junehappylove
 */
public static void main(String[] args) throws IOException, TimeoutException {
	final ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(host);
	factory.setUsername(username);
	factory.setPassword(password);
	factory.setPort(port);
	factory.setVirtualHost(virtualHost);
	Connection connection = factory.newConnection();
	final Channel channel = connection.createChannel();

	channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
	System.out.println("Worker1  Waiting for messages");

	// 每次從隊列獲取的數量
	//channel.basicQos(1);保證一次隻分發一個 
	channel.basicQos(1);

	final Consumer consumer = new DefaultConsumer(channel) {
		@Override
		public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
				byte[] body) throws IOException {
			String message = new String(body, "UTF-8");
			System.out.println("Worker1  Received '" + message + "'");
			try {
				//throw new Exception();
				doWork(message);
			} catch (Exception e) {
				channel.abort();
			} finally {
				System.out.println("Worker1 Done");
				channel.basicAck(envelope.getDeliveryTag(), false);
			}
		}
	};
	//autoAck是否自動回複,
	//如果為true的話,每次生產者隻要發送信息就會從內存中刪除,
	//那麽如果消費者程序異常退出,那麽就無法獲取數據,
	//我們當然是不希望出現這樣的情況,所以才去手動回複,
	//每當消費者收到並處理信息然後在通知生成者。
	//最後從隊列中刪除這條信息。
	//如果消費者異常退出,如果還有其他消費者,
	//那麽就會把隊列中的消息發送給其他消費者,
	//如果沒有,等消費者啟動時候再次發送。
	boolean autoAck = false;
	// 消息消費完成確認
	channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);

}
 
開發者ID:pudoj,項目名稱:june.mq,代碼行數:56,代碼來源:Work1.java

示例14: main

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
/**
 * @param args
 * @throws IOException
 * @throws TimeoutException
 * @date 2017年7月11日 下午5:55:38
 * @writer junehappylove
 */
public static void main(String[] args) throws IOException, TimeoutException {
	final ConnectionFactory factory = new ConnectionFactory();
	factory.setHost(host);
	factory.setUsername(username);
	factory.setPassword(password);
	factory.setPort(port);
	factory.setVirtualHost(virtualHost);
	Connection connection = factory.newConnection();
	final Channel channel = connection.createChannel();

	channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
	System.out.println("Worker2 Waiting for messages");

	// 每次從隊列獲取的數量
	//channel.basicQos(1);保證一次隻分發一個 
	channel.basicQos(1);

	final Consumer consumer = new DefaultConsumer(channel) {
		@Override
		public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
				byte[] body) throws IOException {
			String message = new String(body, "UTF-8");
			System.out.println("Worker2 Received '" + message + "'");
			try {
				//throw new Exception();
				doWork(message);
			} catch (Exception e) {
				channel.abort();
			} finally {
				System.out.println("Worker2 Done");
				channel.basicAck(envelope.getDeliveryTag(), false);
			}
		}
	};
	//autoAck是否自動回複,
	//如果為true的話,每次生產者隻要發送信息就會從內存中刪除,
	//那麽如果消費者程序異常退出,那麽就無法獲取數據,
	//我們當然是不希望出現這樣的情況,所以才去手動回複,
	//每當消費者收到並處理信息然後在通知生成者。
	//最後從隊列中刪除這條信息。
	//如果消費者異常退出,如果還有其他消費者,
	//那麽就會把隊列中的消息發送給其他消費者,
	//如果沒有,等消費者啟動時候再次發送。
	boolean autoAck = false;
	// 消息消費完成確認
	channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);

}
 
開發者ID:pudoj,項目名稱:june.mq,代碼行數:56,代碼來源:Work2.java

示例15: recover

import com.rabbitmq.client.Channel; //導入方法依賴的package包/類
@Override
public void recover() {
	try {
		componentManager.getHeartbeatMQAccessService().start();
		stateManager = componentManager.getStateManager();
		
		LOG.info("Start to read messages from MQ ...");
		final Channel channel = componentManager.getHeartbeatMQAccessService().getChannel();
		final String q = componentManager.getHeartbeatMQAccessService().getQueueName();
		
		while(true) {
			GetResponse response = channel.basicGet(q, false);
			if(response != null) {
				long deliveryTag = response.getEnvelope().getDeliveryTag();
				String message = new String(response.getBody(), "UTF-8");
				LOG.info("Received msg: deliveryTag=" + deliveryTag + ", message=" + message);
				
				JSONObject result = JSONObject.parseObject(message);
				if(result.containsKey(JSONKeys.TYPE)) {
					String type = result.getString(JSONKeys.TYPE);
					switch(type) {
						case ScheduledConstants.HEARTBEAT_TYPE_TASK_PROGRESS:
							
							// {"type":"taskProgress","platform_id":"7fe13e9879314da38bb7abc8b61657bb","tasks":[{"result":{"traceId":"1480402382967","callId":"1","resultCount":"1423","message":"SUCCESS","status":5},"jobId":1,"taskType":1,"taskId":1,"seqNo":1,"status":"SUCCEEDED"}]}
							// add flag 'needRecovering' to a tasks response
							result.put(ScheduledConstants.NEED_RECOVERING, ScheduledConstants.YES);
							needRecoveredTaskQueue.add(result);
							channel.basicAck(deliveryTag, false);
							break;
					}
				} else {
					channel.basicAck(deliveryTag, false);
				}
			} else {
				break;
			}
		}
		LOG.info("Complete to read MQ messages: q=" + q);
		
		// update Redis statuses
		recoverRedisStates();
		
		// recover job/task statuses
		processPendingTaskResponses();
	} catch (Exception e) {
		LOG.error("Recovery failure:", e);
		Throwables.propagate(e);
	} finally {
		componentManager.getHeartbeatMQAccessService().stop();
	}
}
 
開發者ID:shirdrn,項目名稱:scheduled,代碼行數:52,代碼來源:RecoveryManagerImpl.java


注:本文中的com.rabbitmq.client.Channel.basicAck方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。