Package org.springframework.amqp.rabbit.core

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


        public RabbitMQMessageListener(SpringAMQPEndpoint endpoint) {
            this.listenerContainer = new SimpleMessageListenerContainer();
            this.listenerContainer.setTaskExecutor(new SpringAMQPExecutor(endpoint));

            RabbitTemplate template = (RabbitTemplate) endpoint.getAmqpTemplate();
            if(template != null) {
                this.msgConverter = template.getMessageConverter();
                this.listenerContainer.setConnectionFactory(template.getConnectionFactory());
            } else {
                LOG.error("No AMQP Template found! Cannot initialize message conversion or connections!");
            }

            this.listenerContainer.setQueueNames(endpoint.getQueueName());
View Full Code Here


            SpringAMQPMessage inMessage = new SpringAMQPMessage(message);
            exchange.setIn(inMessage); //Swap out the old message format

            MessageConverter msgConverter;
            if(endpoint.getAmqpTemplate() instanceof RabbitTemplate) {
                RabbitTemplate rabbitTemplate = (RabbitTemplate) endpoint.getAmqpTemplate();
                msgConverter = rabbitTemplate.getMessageConverter();
            } else {
                LOG.warn("Cannot find RabbitMQ AMQP Template, falling back to simple message converter");
                msgConverter = new SimpleMessageConverter();
            }
           
View Full Code Here

    return connectionFactory;
  }

  @Override
  public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setRoutingKey(routingKey);
    template.setQueue(queueName);
    return template;
  }
View Full Code Here

  }
 
 
  @Override
  public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setRoutingKey("key.b.a");
    template.setExchange(exchange);
    return template;
  }
View Full Code Here

    container.setQueueName(this.queueName);
    return container;
  }
  @Bean
  public StockLookup stockLookup(){
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setRoutingKey("key.b.a");
    template.setExchange(exchange);
   
    StockLookup lookup = new StockLookup();
    lookup.setRabbitTemplate(template);
    return lookup;
  }
View Full Code Here

    }).when(errorHandler).handleError(any(Throwable.class));
  }

  @Test // AMQP-385
  public void testErrorHandlerThrowsARADRE() throws Exception {
    RabbitTemplate template = this.createTemplate(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(template.getConnectionFactory());
    container.setQueues(queue);
    final CountDownLatch messageReceived = new CountDownLatch(1);
    final CountDownLatch spiedQLogger = new CountDownLatch(1);
    final CountDownLatch errorHandled = new CountDownLatch(1);
    container.setErrorHandler(new ErrorHandler() {

      @Override
      public void handleError(Throwable t) {
        errorHandled.countDown();
        throw new AmqpRejectAndDontRequeueException("foo", t);
      }
    });
    container.setMessageListener(new MessageListener() {

      @Override
      public void onMessage(Message message) {
        try {
          messageReceived.countDown();
          spiedQLogger.await(10, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
        throw new RuntimeException("bar");
      }
    });
    container.start();
    Log logger = spy(TestUtils.getPropertyValue(container, "logger", Log.class));
    new DirectFieldAccessor(container).setPropertyValue("logger", logger);
    when(logger.isWarnEnabled()).thenReturn(true);
    template.convertAndSend(queue.getName(), "baz");
    assertTrue(messageReceived.await(10, TimeUnit.SECONDS));
    Object consumer = TestUtils.getPropertyValue(container, "consumers", Map.class)
        .keySet().iterator().next();
    Log qLogger = spy(TestUtils.getPropertyValue(consumer, "logger", Log.class));
    new DirectFieldAccessor(consumer).setPropertyValue("logger", qLogger);
View Full Code Here

        new RuntimeException("Channel aware listener runtime exception")));
  }

  @Test
  public void testRejectingErrorHandler() throws Exception {
    RabbitTemplate template = createTemplate(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(template.getConnectionFactory());
    MessageListenerAdapter messageListener = new MessageListenerAdapter();
    messageListener.setDelegate(new Object());
    container.setMessageListener(messageListener);

    RabbitAdmin admin = new RabbitAdmin(template.getConnectionFactory());
    Map<String, Object> args = new HashMap<String, Object>();
    args.put("x-dead-letter-exchange", "test.DLE");
    Queue queue = new Queue("", false, false, true, args);
    String testQueueName = admin.declareQueue(queue);
    // Create a DeadLetterExchange and bind a queue to it with the original routing key
    DirectExchange dle = new DirectExchange("test.DLE", false, true);
    admin.declareExchange(dle);
    Queue dlq = new AnonymousQueue();
    admin.declareQueue(dlq);
    admin.declareBinding(BindingBuilder.bind(dlq).to(dle).with(testQueueName));

    container.setQueueNames(testQueueName);
    container.afterPropertiesSet();
    container.start();

    Message message = MessageBuilder.withBody("foo".getBytes())
        .setContentType("text/plain")
        .setContentEncoding("junk")
        .build();
    template.send("", testQueueName, message);

    Message rejected = template.receive(dlq.getName());
    int n = 0;
    while (n++ < 100 && rejected == null) {
      Thread.sleep(100);
      rejected = template.receive(dlq.getName());
    }
    assertTrue("Message did not arrive in DLQ", n < 100);
    assertEquals("foo", new String(rejected.getBody()));


    // Verify that the exception strategy has access to the message
    final AtomicReference<Message> failed = new AtomicReference<Message>();
    ConditionalRejectingErrorHandler eh = new ConditionalRejectingErrorHandler(new FatalExceptionStrategy() {

      @Override
      public boolean isFatal(Throwable t) {
        if (t instanceof ListenerExecutionFailedException) {
          failed.set(((ListenerExecutionFailedException) t).getFailedMessage());
        }
        return t instanceof ListenerExecutionFailedException
            && t.getCause() instanceof MessageConversionException;
      }
    });
    container.setErrorHandler(eh);

    template.send("", testQueueName, message);

    rejected = template.receive(dlq.getName());
    n = 0;
    while (n++ < 100 && rejected == null) {
      Thread.sleep(100);
      rejected = template.receive(dlq.getName());
    }
    assertTrue("Message did not arrive in DLQ", n < 100);
    assertEquals("foo", new String(rejected.getBody()));
    assertNotNull(failed.get());
View Full Code Here

  public void doTest(int messageCount, ErrorHandler errorHandler, CountDownLatch latch, Object listener)
      throws Exception {
    this.errorsHandled = new CountDownLatch(messageCount);
    int concurrentConsumers = 1;
    RabbitTemplate template = createTemplate(concurrentConsumers);

    // Send messages to the queue
    for (int i = 0; i < messageCount; i++) {
      template.convertAndSend(queue.getName(), i + "foo");
    }

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(template.getConnectionFactory());
    container.setMessageListener(listener);
    container.setAcknowledgeMode(AcknowledgeMode.NONE);
    container.setChannelTransacted(false);
    container.setConcurrentConsumers(concurrentConsumers);

    container.setPrefetchCount(messageCount);
    container.setTxSize(messageCount);
    container.setQueueNames(queue.getName());
    container.setErrorHandler(errorHandler);
    container.afterPropertiesSet();
    container.start();

    try {
      boolean waited = latch.await(5000, TimeUnit.MILLISECONDS);
      if (messageCount > 1) {
        assertTrue("Expected to receive all messages before stop", waited);
      }

      assertTrue("Not enough error handling, remaining:" + this.errorsHandled.getCount(),
          this.errorsHandled.await(10, TimeUnit.SECONDS));
      assertNull(template.receiveAndConvert(queue.getName()));
    }
    finally {
      container.shutdown();
    }

    ((DisposableBean) template.getConnectionFactory()).destroy();
  }
View Full Code Here

    ((DisposableBean) template.getConnectionFactory()).destroy();
  }

  private RabbitTemplate createTemplate(int concurrentConsumers) {
    RabbitTemplate template = new RabbitTemplate();
    // SingleConnectionFactory connectionFactory = new SingleConnectionFactory();
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setChannelCacheSize(concurrentConsumers);
    connectionFactory.setPort(BrokerTestUtils.getPort());
    template.setConnectionFactory(connectionFactory);
    return template;
  }
View Full Code Here

    /**
     * @return Rabbit template with fixed reply queue.
     */
    @Bean
    public RabbitTemplate fixedReplyQRabbitTemplate() {
      RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory());
      template.setExchange(ex().getName());
      template.setRoutingKey("test");
      template.setReplyQueue(replyQueue());
      return template;
    }
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.