Package org.springframework.amqp.rabbit.core

Examples of org.springframework.amqp.rabbit.core.RabbitTemplate


  }

  @Test
  public void testMixTransactionalAndNonTransactional() throws Exception {

    RabbitTemplate template1 = new RabbitTemplate(connectionFactory);
    RabbitTemplate template2 = new RabbitTemplate(connectionFactory);
    template1.setChannelTransacted(true);

    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    Queue queue = admin.declareQueue();

    template1.convertAndSend(queue.getName(), "message");
    String result = (String) template2.receiveAndConvert(queue.getName());
    assertEquals("message", result);

    // The channel is not transactional
    exception.expect(AmqpIOException.class);

    template2.execute(new ChannelCallback<Void>() {
      @Override
      public Void doInRabbit(Channel channel) throws Exception {
        // Should be an exception because the channel is not transactional
        channel.txRollback();
        return null;
View Full Code Here


  }

  @Test
  public void testHardErrorAndReconnect() throws Exception {

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    Queue queue = new Queue("foo");
    admin.declareQueue(queue);
    final String route = queue.getName();

    final CountDownLatch latch = new CountDownLatch(1);
    try {
      template.execute(new ChannelCallback<Object>() {
        @Override
        public Object doInRabbit(Channel channel) throws Exception {
          channel.getConnection().addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
              logger.info("Error", cause);
              latch.countDown();
              // This will be thrown on the Connection thread just before it dies, so basically ignored
              throw new RuntimeException(cause);
            }
          });
          String tag = channel.basicConsume(route, new DefaultConsumer(channel));
          // Consume twice with the same tag is a hard error (connection will be reset)
          String result = channel.basicConsume(route, false, tag, new DefaultConsumer(channel));
          fail("Expected IOException, got: " + result);
          return null;
        }
      });
      fail("Expected AmqpIOException");
    } catch (AmqpIOException e) {
      // expected
    }
    template.convertAndSend(route, "message");
    assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
    String result = (String) template.receiveAndConvert(route);
    assertEquals("message", result);
    result = (String) template.receiveAndConvert(route);
    assertEquals(null, result);
  }
View Full Code Here

        TestUtils.getPropertyValue(template, "receiveConnectionFactorySelectorExpression.expression"));
  }

  @Test
  public void testKitchenSink() throws Exception {
    RabbitTemplate template = beanFactory.getBean("kitchenSink", RabbitTemplate.class);
    assertNotNull(template);
    assertTrue(template.getMessageConverter() instanceof SerializerMessageConverter);
    DirectFieldAccessor accessor = new DirectFieldAccessor(template);
    assertEquals("foo", accessor.getPropertyValue("correlationKey"));
    assertSame(beanFactory.getBean(RetryTemplate.class), accessor.getPropertyValue("retryTemplate"));
    assertSame(beanFactory.getBean(RecoveryCallback.class), accessor.getPropertyValue("recoveryCallback"));
  }
View Full Code Here

    assertSame(beanFactory.getBean(RecoveryCallback.class), accessor.getPropertyValue("recoveryCallback"));
  }

  @Test
  public void testWithReplyQ() throws Exception {
    RabbitTemplate template = beanFactory.getBean("withReplyQ", RabbitTemplate.class);
    assertNotNull(template);
    DirectFieldAccessor dfa = new DirectFieldAccessor(template);
    assertNull(dfa.getPropertyValue("correlationKey"));
    Queue queue = (Queue) dfa.getPropertyValue("replyQueue");
    assertNotNull(queue);
View Full Code Here

   * @param connectionFactory the Rabbit ConnectionFactory to create a RabbitTemplate for
   * @return the new RabbitTemplate instance
   * @see #setConnectionFactory
   */
  protected RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
    return new RabbitTemplate(connectionFactory);
  }
View Full Code Here

    assertEquals("initGatway called", test.size(), 1);
  }

  @Test
  public void testRabbitGatewaySupportWithJmsTemplate() throws Exception {
    RabbitTemplate template = new RabbitTemplate();
    final List<String> test = new ArrayList<String>();
    RabbitGatewaySupport gateway = new RabbitGatewaySupport() {
      protected void initGateway() {
        test.add("test");
      }
View Full Code Here

   */
  protected class EventSender implements Runnable {
    @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);
            MDC.put(APPLICATION_ID, 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);
            }
            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
View Full Code Here

   */
  protected class EventSender implements Runnable {
    @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;
          // Set applicationId, if we're using one
          if (null != applicationId) {
            amqpProps.setAppId(applicationId);
            logEvent.getLoggerContextVO().getPropertyMap().put(APPLICATION_ID, applicationId);
          }

          routingKey = routingKeyLayout.doLayout(logEvent);

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

            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
View Full Code Here

    Queue queue = beanFactory.getBean("arguments", Queue.class);
    assertNotNull(queue);
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(BrokerTestUtils.getPort());
    connectionFactory.setHost("localhost");
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    RabbitAdmin rabbitAdmin = new RabbitAdmin(template.getConnectionFactory());
    rabbitAdmin.deleteQueue(queue.getName());
    rabbitAdmin.declareQueue(queue);

    assertEquals(100L, queue.getArguments().get("x-message-ttl"));
    template.convertAndSend(queue.getName(), "message");

    Thread.sleep(200);
    String result = (String) template.receiveAndConvert(queue.getName());
    assertEquals(null, result);

    connectionFactory.destroy();

  }
View Full Code Here

TOP

Related Classes of org.springframework.amqp.rabbit.core.RabbitTemplate

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.