List of usage examples for com.rabbitmq.client Envelope getDeliveryTag
public long getDeliveryTag()
From source file:com.shopwiki.roger.MessagingUtil.java
License:Apache License
public static String prettyPrint(Envelope envelope) { StringBuilder sb = new StringBuilder(); sb.append("\t" + "Exchange: " + envelope.getExchange() + "\n"); sb.append("\t" + "RoutingKey: " + envelope.getRoutingKey() + "\n"); sb.append("\t" + "DeliveryTag: " + envelope.getDeliveryTag() + "\n"); sb.append("\t" + "isRedeliver: " + envelope.isRedeliver()); return sb.toString(); }
From source file:com.shopwiki.roger.rpc.RequestConsumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties requestProps, byte[] body) throws IOException { I request = null;/* w w w . j a v a2 s .c o m*/ ResponseStatus status = null; Object response = null; Throwable thrown = null; long timeTaken = -1; try { long startTime = System.currentTimeMillis(); try { request = MessagingUtil.getDeliveryBody(body, requestType); } catch (Exception e) { response = new ExceptionResponse(e); status = ResponseStatus.MALFORMED_REQUEST; thrown = e; } if (DEBUG) { System.out.println( "*** RequestHandler " + handler.getClass().getCanonicalName() + " RECEIVED REQUEST ***"); System.out.println("*** consumerTag: " + consumerTag); System.out.println("*** envelope:\n" + MessagingUtil.prettyPrint(envelope)); System.out.println("*** requestProps:\n" + MessagingUtil.prettyPrint(requestProps)); System.out.println("*** request: " + MessagingUtil.prettyPrintMessage(request)); System.out.println(); } if (request != null) { try { response = handler.handleRequest(request); status = ResponseStatus.OK; } catch (NackException e) { thrown = e; channel.basicNack(envelope.getDeliveryTag(), false, true); return; } catch (IllegalArgumentException e) { response = new ExceptionResponse(e); status = ResponseStatus.INVALID_REQUEST; thrown = e; } catch (Throwable e) { response = new ExceptionResponse(e); status = ResponseStatus.HANDLER_ERROR; thrown = e; } } timeTaken = System.currentTimeMillis() - startTime; // Ack before or after the reply is sent ??? channel.basicAck(envelope.getDeliveryTag(), false); String replyTo = requestProps.getReplyTo(); String correlationId = requestProps.getCorrelationId(); if (correlationId != null && replyTo != null) { Map<String, Object> headers = new LinkedHashMap<String, Object>(); headers.put("status", String.valueOf(status)); headers.put("handler_time_millis", String.valueOf(timeTaken)); headers.put("hostname", hostname); BasicProperties.Builder replyProps = new BasicProperties.Builder(); replyProps = replyProps.headers(headers); replyProps = replyProps.correlationId(correlationId); // TODO: delivery mode ??? MessagingUtil.sendResponse(channel, replyTo, response, replyProps); } } catch (Throwable e) { status = ResponseStatus.NUCLEAR; thrown = e; } finally { if (pps != null) { pps.process(handler, queueName, status, request, response, thrown, timeTaken); } } }
From source file:com.springsource.insight.plugin.rabbitmqClient.RabbitMQConsumerCollectionAspectTest.java
License:Apache License
void assertOperation(Envelope envelope, BasicProperties props, byte[] body) { Operation op = getLastEntered(); assertEquals(OperationType.valueOf("rabbitmq-client-consumer"), op.getType()); assertEquals("Consume", op.getLabel()); assertEquals(Integer.valueOf(body.length), op.get("bytes", Integer.class)); OperationMap envMap = op.get("envelope", OperationMap.class); assertNotNull(envMap);// ww w . j av a2 s . c o m assertEquals(Long.valueOf(envelope.getDeliveryTag()), envMap.get("deliveryTag", Long.class)); assertEquals(envelope.getExchange(), envMap.get("exchange", String.class)); assertEquals(envelope.getRoutingKey(), envMap.get("routingKey", String.class)); assertNull(op.get("connectionUrl")); assertNull(op.get("serverVersion")); assertNull(op.get("clientVersion")); OperationMap propsMap = op.get("props", OperationMap.class); assertEquals(props.getAppId(), propsMap.get("App Id")); assertEquals(props.getContentEncoding(), propsMap.get("Content Encoding")); assertEquals(props.getContentType(), propsMap.get("Content Type")); assertEquals(props.getDeliveryMode(), propsMap.get("Delivery Mode")); assertEquals(props.getExpiration(), propsMap.get("Expiration")); }
From source file:com.streamsets.pipeline.stage.origin.rabbitmq.RabbitSource.java
License:Apache License
@Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { if (!isConnected() && !conf.advanced.automaticRecoveryEnabled) { // If we don't have automatic recovery enabled and the connection is closed, we should stop the pipeline. throw new StageException(Errors.RABBITMQ_05); }//from ww w .j av a 2 s. c om long maxTime = System.currentTimeMillis() + conf.basicConfig.maxWaitTime; int maxRecords = Math.min(maxBatchSize, conf.basicConfig.maxBatchSize); int numRecords = 0; String nextSourceOffset = lastSourceOffset; while (System.currentTimeMillis() < maxTime && numRecords < maxRecords) { try { RabbitMessage message = messages.poll(conf.basicConfig.maxWaitTime, TimeUnit.MILLISECONDS); if (message == null) { continue; } String recordId = message.getEnvelope().toString(); List<Record> records = parseRabbitMessage(recordId, message.getBody()); for (Record record : records) { Envelope envelope = message.getEnvelope(); BasicProperties properties = message.getProperties(); Record.Header outHeader = record.getHeader(); if (envelope != null) { setHeaderIfNotNull(outHeader, "deliveryTag", envelope.getDeliveryTag()); setHeaderIfNotNull(outHeader, "exchange", envelope.getExchange()); setHeaderIfNotNull(outHeader, "routingKey", envelope.getRoutingKey()); setHeaderIfNotNull(outHeader, "redelivered", envelope.isRedeliver()); } setHeaderIfNotNull(outHeader, "contentType", properties.getContentType()); setHeaderIfNotNull(outHeader, "contentEncoding", properties.getContentEncoding()); setHeaderIfNotNull(outHeader, "deliveryMode", properties.getDeliveryMode()); setHeaderIfNotNull(outHeader, "priority", properties.getPriority()); setHeaderIfNotNull(outHeader, "correlationId", properties.getCorrelationId()); setHeaderIfNotNull(outHeader, "replyTo", properties.getReplyTo()); setHeaderIfNotNull(outHeader, "expiration", properties.getExpiration()); setHeaderIfNotNull(outHeader, "messageId", properties.getMessageId()); setHeaderIfNotNull(outHeader, "timestamp", properties.getTimestamp()); setHeaderIfNotNull(outHeader, "messageType", properties.getType()); setHeaderIfNotNull(outHeader, "userId", properties.getUserId()); setHeaderIfNotNull(outHeader, "appId", properties.getAppId()); Map<String, Object> inHeaders = properties.getHeaders(); if (inHeaders != null) { for (Map.Entry<String, Object> pair : inHeaders.entrySet()) { // I am concerned about overlapping with the above headers but it seems somewhat unlikely // in addition the behavior of copying these attributes in with no custom prefix is // how the jms origin behaves setHeaderIfNotNull(outHeader, pair.getKey(), pair.getValue()); } } batchMaker.addRecord(record); nextSourceOffset = outHeader.getAttribute("deliveryTag"); numRecords++; } } catch (InterruptedException e) { LOG.warn("Pipeline is shutting down."); } } return nextSourceOffset; }
From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpoint.java
License:Apache License
/** * Sets up a consumer that passes received messages to the * {@link MessageEndpointListener}s./* w ww.j av a 2 s. c o m*/ */ private void setUpConsumer() throws IOException { DefaultConsumer consumer = new DefaultConsumer(this.channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); super.getChannel().basicAck(deliveryTag, false); if (!properties.getAppId().equals(AMQPEndpoint.this.uuid.toString())) { MessageManifest mm = MessageFactory.decode(body); try { URI responseURI = new URIBuilder().routingKey(properties.getReplyTo()) .instanceName(getName()).build(); mm.setResponseURI(responseURI); } catch (URISyntaxException e) { // this should never happen! LOG.warn("Unable to create response URI for incoming message", e); } notifyMessageEndpointListeners(mm); } } }; if (this.listenForTasks) { String queueName = QUEUE_NAME_TASKS + this.routingKey; this.channel.basicConsume(queueName, false, consumer); } this.channel.basicConsume(this.exclusiveQueueName, false, consumer); // listening to the remote shutdown ShutdownListener shutdownListener = new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException cause) { shutdown(); } }; this.channel.addShutdownListener(shutdownListener); // if (this.channel.isOpen()) { // handler.handleConnectionEvent(true); // } }
From source file:edu.iu.messaging.service.core.impl.CustomerConsumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Message message = new Message(); try {/*from www . jav a 2 s. c om*/ logger.info("handleDelivery() -> Handling message delivery. Consumer Tag : " + consumerTag); ThriftUtils.createThriftFromBytes(body, message); Customer experimentEvent = new Customer(); ThriftUtils.createThriftFromBytes(message.getEvent(), experimentEvent); TBase event = experimentEvent; MessageContext messageContext = new MessageContext(event, message.getMessageId(), envelope.getDeliveryTag()); handler.onMessage(messageContext); //sendAck(deliveryTag); } catch (TException e) { logger.error("handleDelivery() -> Error handling delivery. Consumer Tag : " + consumerTag, e); } }
From source file:edu.iu.messaging.service.core.impl.OrderConsumer.java
License:Apache License
@Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { Message message = new Message(); try {//from w w w .ja v a 2 s.c o m logger.info("handleDelivery() -> Handling message delivery. Consumer Tag : " + consumerTag); ThriftUtils.createThriftFromBytes(body, message); Orders experimentEvent = new Orders(); ThriftUtils.createThriftFromBytes(message.getEvent(), experimentEvent); TBase event = event = experimentEvent; MessageContext messageContext = new MessageContext(event, message.getMessageId(), envelope.getDeliveryTag()); handler.onMessage(messageContext); //sendAck(deliveryTag); } catch (TException e) { logger.error("handleDelivery() -> Error handling delivery. Consumer Tag : " + consumerTag, e); } }
From source file:genqa.ExportRabbitMQVerifier.java
License:Open Source License
private Consumer createConsumer(final Channel channel) { return new DefaultConsumer(channel) { @Override/*from w ww . j a v a 2 s . c om*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); String row[] = ExportOnServerVerifier.RoughCSVTokenizer.tokenize(new String(body, Charsets.UTF_8)); if (row.length != 29) { return; } ExportOnServerVerifier.ValidationErr err = null; try { err = ExportOnServerVerifier.verifyRow(row); } catch (ExportOnServerVerifier.ValidationErr validationErr) { validationErr.printStackTrace(); } if (err != null) { System.out.println("ERROR in validation: " + err.toString()); } if (++m_verifiedRows % VALIDATION_REPORT_INTERVAL == 0) { System.out.println("Verified " + m_verifiedRows + " rows."); } channel.basicAck(deliveryTag, false); } }; }
From source file:io.opentracing.contrib.rabbitmq.TracingTest.java
License:Apache License
@Test public void basicConsume() throws Exception { String exchangeName = "basicConsumeExchange"; String queueName = "basicConsumeQueue"; String routingKey = "#"; channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); byte[] messageBodyBytes = "Hello, world!".getBytes(); channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); final CountDownLatch latch = new CountDownLatch(1); channel.basicConsume(queueName, false, new DefaultConsumer(channel) { @Override// ww w . ja v a 2 s .c om public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { long deliveryTag = envelope.getDeliveryTag(); channel.basicAck(deliveryTag, false); latch.countDown(); } }); latch.await(30, TimeUnit.SECONDS); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); int tries = 10; while (tries > 0 && finishedSpans.size() < 2) { TimeUnit.SECONDS.sleep(1L); finishedSpans = mockTracer.finishedSpans(); tries--; } assertEquals(2, finishedSpans.size()); checkSpans(finishedSpans); assertNull(mockTracer.activeSpan()); }
From source file:io.qdb.server.input.RabbitMQInputHandler.java
License:Apache License
@Override public void start(final Sink sink) throws Exception { this.sink = sink; final Channel c = ensureChannel(); c.basicConsume(queue, autoAck, "qdb:" + inputPath, new DefaultConsumer(c) { @Override/* w ww . j a v a 2s . com*/ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { boolean ok = false; try { sink.append(envelope.getRoutingKey(), body); if (!autoAck) c.basicAck(envelope.getDeliveryTag(), false); ok = true; } catch (Exception e) { sink.error(e); } finally { if (!ok) { try { // todo should probably sit on the message for a bit before nacking to prevent storm c.basicNack(envelope.getDeliveryTag(), false, true); } catch (IOException e) { log.debug("Error nacking message: " + e, e); } } } } }); }