Ejemplo n.º 1
0
 @Override
 public Object invoke(MethodInvocation invocation) throws Throwable {
   String id = null;
   Message message = null;
   boolean redelivered = false;
   try {
     message = (Message) invocation.getArguments()[1];
     MessageProperties messageProperties = message.getMessageProperties();
     if (messageProperties.getMessageId() == null) {
       id = UUID.randomUUID().toString();
       messageProperties.setMessageId(id);
     }
     redelivered = messageProperties.isRedelivered();
     return invocation.proceed();
   } catch (Exception e) {
     if (id != null && redelivered) {
       if (logger.isDebugEnabled()) {
         logger.debug("Canceling delivery of retried message that has no ID");
       }
       throw new ListenerExecutionFailedException(
           "Cannot retry message without an ID",
           new AmqpRejectAndDontRequeueException(e),
           message);
     } else {
       throw e;
     }
   } finally {
     if (id != null) {
       retryContextCache.remove(id);
     }
   }
 }
 public MessageProperties toMessageProperties(
     final BasicProperties source, final Envelope envelope, final String charset) {
   MessageProperties target = new MessageProperties();
   Map<String, Object> headers = source.getHeaders();
   if (!CollectionUtils.isEmpty(headers)) {
     for (Map.Entry<String, Object> entry : headers.entrySet()) {
       String key = entry.getKey();
       if (MessageProperties.X_DELAY.equals(key)) {
         Object value = entry.getValue();
         if (value instanceof Integer) {
           target.setReceivedDelay((Integer) value);
         }
       } else {
         target.setHeader(key, convertLongStringIfNecessary(entry.getValue(), charset));
       }
     }
   }
   target.setTimestamp(source.getTimestamp());
   target.setMessageId(source.getMessageId());
   target.setReceivedUserId(source.getUserId());
   target.setAppId(source.getAppId());
   target.setClusterId(source.getClusterId());
   target.setType(source.getType());
   Integer deliveryMode = source.getDeliveryMode();
   if (deliveryMode != null) {
     target.setReceivedDeliveryMode(MessageDeliveryMode.fromInt(deliveryMode));
   }
   target.setDeliveryMode(null);
   target.setExpiration(source.getExpiration());
   target.setPriority(source.getPriority());
   target.setContentType(source.getContentType());
   target.setContentEncoding(source.getContentEncoding());
   String correlationId = source.getCorrelationId();
   if (StringUtils.hasText(correlationId)) {
     target.setCorrelationId(source.getCorrelationId());
   }
   String replyTo = source.getReplyTo();
   if (replyTo != null) {
     target.setReplyTo(replyTo);
   }
   if (envelope != null) {
     target.setReceivedExchange(envelope.getExchange());
     target.setReceivedRoutingKey(envelope.getRoutingKey());
     target.setRedelivered(envelope.isRedeliver());
     target.setDeliveryTag(envelope.getDeliveryTag());
   }
   return target;
 }
Ejemplo n.º 3
0
 public Object invoke(MethodInvocation invocation) throws Throwable {
   String id = null;
   try {
     Message message = (Message) invocation.getArguments()[1];
     MessageProperties messageProperties = message.getMessageProperties();
     if (messageProperties.getMessageId() == null) {
       id = UUID.randomUUID().toString();
       messageProperties.setMessageId(id);
     }
     return invocation.proceed();
   } catch (Throwable t) {
     throw new AmqpRejectAndDontRequeueException("Cannot retry message without an ID", t);
   } finally {
     if (id != null) {
       retryContextCache.remove(id);
     }
   }
 }
  @Override
  public void run() {
    logger.info("Running...");
    while (!stopped) {
      if (generating) {
        Order order = generateOrder();
        logger.info("Sending order: " + order.toString());

        // Create Message
        MessageProperties mp = new MessageProperties();
        mp.setMessageId(order.getTransactionId());
        Message message = new Message(order.toBytes(), mp);

        // Send order
        ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
        RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
        rabbitTemplate.convertAndSend(message);

        OrderRepository orderRepository = ctx.getBean(OrderRepository.class);
        orderRepository.save(order);
        logger.info("Sent order: " + order.toString());
      } else {
        logger.info("Not generating...");
        try {
          Thread.sleep(500);
        } catch (Exception e) {
          return;
        }
      }
      try {
        Thread.sleep(100);
      } catch (Exception e) {
        return;
      }
    }
  }
Ejemplo n.º 5
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          ILoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLoggerName();
          Level level = logEvent.getLevel();

          MessageProperties amqpProps = new MessageProperties();
          amqpProps.setDeliveryMode(deliveryMode);
          amqpProps.setContentType(contentType);
          if (null != contentEncoding) {
            amqpProps.setContentEncoding(contentEncoding);
          }
          amqpProps.setHeader(CATEGORY_NAME, name);
          amqpProps.setHeader(CATEGORY_LEVEL, level.toString());
          if (generateId) {
            amqpProps.setMessageId(UUID.randomUUID().toString());
          }

          // Set timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          Map<String, String> props = event.getProperties();
          Set<Entry<String, String>> entrySet = props.entrySet();
          for (Entry<String, String> entry : entrySet) {
            amqpProps.setHeader(entry.getKey(), entry.getValue());
          }
          String[] location = locationLayout.doLayout(logEvent).split("\\|");
          if (!"?".equals(location[0])) {
            amqpProps.setHeader(
                "location", String.format("%s.%s()[%s]", location[0], location[1], location[2]));
          }
          String msgBody;
          String routingKey = routingKeyLayout.doLayout(logEvent);
          // Set applicationId, if we're using one
          if (applicationId != null) {
            amqpProps.setAppId(applicationId);
          }

          if (abbreviator != null && logEvent instanceof LoggingEvent) {
            ((LoggingEvent) logEvent).setLoggerName(abbreviator.abbreviate(name));
            msgBody = layout.doLayout(logEvent);
            ((LoggingEvent) logEvent).setLoggerName(name);
          } else {
            msgBody = layout.doLayout(logEvent);
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message = new Message(msgBody.getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                message = new Message(msgBody.getBytes(), amqpProps); // NOSONAR (default charset)
              }
            }

            message = postProcessMessageBeforeSend(message, event);
            rabbitTemplate.send(exchangeName, routingKey, message);
          } catch (AmqpException e) {
            int retries = event.incrementRetries();
            if (retries < maxSenderRetries) {
              // Schedule a retry based on the number of times I've tried to re-send this
              retryTimer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      events.add(event);
                    }
                  },
                  (long) (Math.pow(retries, Math.log(retries)) * 1000));
            } else {
              addError(
                  "Could not send log message "
                      + logEvent.getMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
Ejemplo n.º 6
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          LoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLogger().getName();
          Level level = logEvent.getLevel();

          MessageProperties amqpProps = new MessageProperties();
          amqpProps.setDeliveryMode(deliveryMode);
          amqpProps.setContentType(contentType);
          if (null != contentEncoding) {
            amqpProps.setContentEncoding(contentEncoding);
          }
          amqpProps.setHeader(CATEGORY_NAME, name);
          amqpProps.setHeader(CATEGORY_LEVEL, level.toString());
          if (generateId) {
            amqpProps.setMessageId(UUID.randomUUID().toString());
          }

          // Set applicationId, if we're using one
          if (null != applicationId) {
            amqpProps.setAppId(applicationId);
          }

          // Set timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          @SuppressWarnings("rawtypes")
          Map props = event.getProperties();
          @SuppressWarnings("unchecked")
          Set<Entry<?, ?>> entrySet = props.entrySet();
          for (Entry<?, ?> entry : entrySet) {
            amqpProps.setHeader(entry.getKey().toString(), entry.getValue());
          }
          LocationInfo locInfo = logEvent.getLocationInformation();
          if (!"?".equals(locInfo.getClassName())) {
            amqpProps.setHeader(
                "location",
                String.format(
                    "%s.%s()[%s]",
                    locInfo.getClassName(), locInfo.getMethodName(), locInfo.getLineNumber()));
          }

          StringBuilder msgBody;
          String routingKey;
          synchronized (layoutMutex) {
            msgBody = new StringBuilder(layout.format(logEvent));
            routingKey = routingKeyLayout.format(logEvent);
          }
          if (layout.ignoresThrowable() && null != logEvent.getThrowableInformation()) {
            ThrowableInformation tinfo = logEvent.getThrowableInformation();
            for (String line : tinfo.getThrowableStrRep()) {
              msgBody.append(String.format("%s%n", line));
            }
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message =
                    new Message(msgBody.toString().getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                /* fall back to default */
              }
            }
            if (message == null) {
              message =
                  new Message(
                      msgBody.toString().getBytes(), amqpProps); // NOSONAR (default charset)
            }
            message = postProcessMessageBeforeSend(message, event);
            rabbitTemplate.send(exchangeName, routingKey, message);
          } catch (AmqpException e) {
            int retries = event.incrementRetries();
            if (retries < maxSenderRetries) {
              // Schedule a retry based on the number of times I've tried to re-send this
              retryTimer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      events.add(event);
                    }
                  },
                  (long) (Math.pow(retries, Math.log(retries)) * 1000));
            } else {
              errorHandler.error(
                  "Could not send log message "
                      + logEvent.getRenderedMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e,
                  ErrorCode.WRITE_FAILURE,
                  logEvent);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
  /**
   * Maps headers from a Spring Integration MessageHeaders instance to the MessageProperties of an
   * AMQP Message.
   */
  @Override
  protected void populateStandardHeaders(
      Map<String, Object> headers, MessageProperties amqpMessageProperties) {
    String appId = getHeaderIfAvailable(headers, AmqpHeaders.APP_ID, String.class);
    if (StringUtils.hasText(appId)) {
      amqpMessageProperties.setAppId(appId);
    }
    String clusterId = getHeaderIfAvailable(headers, AmqpHeaders.CLUSTER_ID, String.class);
    if (StringUtils.hasText(clusterId)) {
      amqpMessageProperties.setClusterId(clusterId);
    }
    String contentEncoding =
        getHeaderIfAvailable(headers, AmqpHeaders.CONTENT_ENCODING, String.class);
    if (StringUtils.hasText(contentEncoding)) {
      amqpMessageProperties.setContentEncoding(contentEncoding);
    }
    Long contentLength = getHeaderIfAvailable(headers, AmqpHeaders.CONTENT_LENGTH, Long.class);
    if (contentLength != null) {
      amqpMessageProperties.setContentLength(contentLength);
    }
    String contentType = this.extractContentTypeAsString(headers);

    if (StringUtils.hasText(contentType)) {
      amqpMessageProperties.setContentType(contentType);
    }
    Object correlationId = headers.get(AmqpHeaders.CORRELATION_ID);
    if (correlationId instanceof byte[]) {
      amqpMessageProperties.setCorrelationId((byte[]) correlationId);
    }
    MessageDeliveryMode deliveryMode =
        getHeaderIfAvailable(headers, AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.class);
    if (deliveryMode != null) {
      amqpMessageProperties.setDeliveryMode(deliveryMode);
    }
    Long deliveryTag = getHeaderIfAvailable(headers, AmqpHeaders.DELIVERY_TAG, Long.class);
    if (deliveryTag != null) {
      amqpMessageProperties.setDeliveryTag(deliveryTag);
    }
    String expiration = getHeaderIfAvailable(headers, AmqpHeaders.EXPIRATION, String.class);
    if (StringUtils.hasText(expiration)) {
      amqpMessageProperties.setExpiration(expiration);
    }
    Integer messageCount = getHeaderIfAvailable(headers, AmqpHeaders.MESSAGE_COUNT, Integer.class);
    if (messageCount != null) {
      amqpMessageProperties.setMessageCount(messageCount);
    }
    String messageId = getHeaderIfAvailable(headers, AmqpHeaders.MESSAGE_ID, String.class);
    if (StringUtils.hasText(messageId)) {
      amqpMessageProperties.setMessageId(messageId);
    }
    Integer priority = getHeaderIfAvailable(headers, MessageHeaders.PRIORITY, Integer.class);
    if (priority != null) {
      amqpMessageProperties.setPriority(priority);
    }
    String receivedExchange =
        getHeaderIfAvailable(headers, AmqpHeaders.RECEIVED_EXCHANGE, String.class);
    if (StringUtils.hasText(receivedExchange)) {
      amqpMessageProperties.setReceivedExchange(receivedExchange);
    }
    String receivedRoutingKey =
        getHeaderIfAvailable(headers, AmqpHeaders.RECEIVED_ROUTING_KEY, String.class);
    if (StringUtils.hasText(receivedRoutingKey)) {
      amqpMessageProperties.setReceivedRoutingKey(receivedRoutingKey);
    }
    Boolean redelivered = getHeaderIfAvailable(headers, AmqpHeaders.REDELIVERED, Boolean.class);
    if (redelivered != null) {
      amqpMessageProperties.setRedelivered(redelivered);
    }
    String replyTo = getHeaderIfAvailable(headers, AmqpHeaders.REPLY_TO, String.class);
    if (replyTo != null) {
      amqpMessageProperties.setReplyTo(replyTo);
    }
    Date timestamp = getHeaderIfAvailable(headers, AmqpHeaders.TIMESTAMP, Date.class);
    if (timestamp != null) {
      amqpMessageProperties.setTimestamp(timestamp);
    }
    String type = getHeaderIfAvailable(headers, AmqpHeaders.TYPE, String.class);
    if (type != null) {
      amqpMessageProperties.setType(type);
    }
    String userId = getHeaderIfAvailable(headers, AmqpHeaders.USER_ID, String.class);
    if (StringUtils.hasText(userId)) {
      amqpMessageProperties.setUserId(userId);
    }
    String replyCorrelation =
        getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_CORRELATION, String.class);
    if (StringUtils.hasLength(replyCorrelation)) {
      amqpMessageProperties.setHeader("spring_reply_correlation", replyCorrelation);
    }
    String replyToStack =
        getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_TO_STACK, String.class);
    if (StringUtils.hasLength(replyToStack)) {
      amqpMessageProperties.setHeader("spring_reply_to", replyToStack);
    }
  }