Example usage for org.springframework.amqp.rabbit.connection CachingConnectionFactory CachingConnectionFactory

List of usage examples for org.springframework.amqp.rabbit.connection CachingConnectionFactory CachingConnectionFactory

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.connection CachingConnectionFactory CachingConnectionFactory.

Prototype

public CachingConnectionFactory() 

Source Link

Document

Create a new CachingConnectionFactory initializing the hostname to be the value returned from InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.

Usage

From source file:com.noriental.solr.config.test.BrokerRunning.java

@Override
public Statement apply(Statement base, Description description) {

    // Check at the beginning, so this can be used as a static field
    if (assumeOnline) {
        Assume.assumeTrue(brokerOnline.get(port));
    } else {/*from w  w w .j a va2  s  . c  o  m*/
        Assume.assumeTrue(brokerOffline.get(port));
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost("localhost");

    try {

        connectionFactory.setPort(port);
        if (StringUtils.hasText(hostName)) {
            connectionFactory.setHost(hostName);
        }
        RabbitAdmin admin = new RabbitAdmin(connectionFactory);

        for (Queue queue : queues) {
            String queueName = queue.getName();

            if (purge) {
                logger.debug("Deleting queue: " + queueName);
                // Delete completely - gets rid of consumers and bindings as well
                admin.deleteQueue(queueName);
            }

            if (isDefaultQueue(queueName)) {
                // Just for test probe.
                admin.deleteQueue(queueName);
            } else {
                admin.declareQueue(queue);
            }
        }
        brokerOffline.put(port, false);
        if (!assumeOnline) {
            Assume.assumeTrue(brokerOffline.get(port));
        }

        if (this.management) {
            Client client = new Client("http://localhost:15672/api/", "guest", "guest");
            if (!client.alivenessTest("/")) {
                throw new RuntimeException(
                        "Aliveness test failed for localhost:15672 guest/quest; " + "management not available");
            }
        }
    } catch (AmqpTimeoutException e) {
        fail("Timed out getting connection");
    } catch (Exception e) {
        logger.warn("Not executing tests because basic connectivity test failed", e);
        brokerOnline.put(port, false);
        if (assumeOnline) {
            Assume.assumeNoException(e);
        }
    } finally {
        connectionFactory.destroy();
    }

    return super.apply(base, description);

}

From source file:amqp.spring.camel.component.SpringAMQPConsumerTest.java

@Override
protected CamelContext createCamelContext() throws Exception {
    CachingConnectionFactory factory = new CachingConnectionFactory();
    RabbitTemplate amqpTemplate = new RabbitTemplate(factory);
    //The JSON converter stresses marshalling more than the default converter
    amqpTemplate.setMessageConverter(new JsonMessageConverter());
    SpringAMQPComponent amqpComponent = new SpringAMQPComponent(factory);
    amqpComponent.setAmqpTemplate(amqpTemplate);

    CamelContext camelContext = super.createCamelContext();
    camelContext.addComponent("spring-amqp", amqpComponent);
    return camelContext;
}

From source file:com.noriental.solr.config.test.BrokerRunning.java

public void removeTestQueues() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setHost("localhost");
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    for (Queue queue : this.queues) {
        admin.deleteQueue(queue.getName());
    }//  w  w  w. j a v  a  2s .c  om
    connectionFactory.destroy();
}

From source file:vn.topmedia.monitor.MonitorAppender.java

@Override
public void append(LoggingEvent event) {
    if (null == senderPool) {
        synchronized (mutex) {
            connectionFactory = new CachingConnectionFactory();
            connectionFactory.setHost(host);
            connectionFactory.setPort(port);
            connectionFactory.setUsername(username);
            connectionFactory.setPassword(password);
            connectionFactory.setVirtualHost(virtualHost);
            maybeDeclareExchange();//from   w  w  w  . j a  v a  2  s  .  c o  m
            exchangeDeclared.set(true);

            startSenders();
        }
    }
    events.add(new Event(event, event.getProperties()));
}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Before
public void setup() {
    this.connectionFactory = new CachingConnectionFactory();
    this.connectionFactory.setHost("localhost");
    this.connectionFactory.setPort(BrokerTestUtils.getPort());
    scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(1);/*from w w w.  ja  v  a 2s  . c o  m*/
    scheduler.initialize();
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Before
public void create() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setPort(BrokerTestUtils.getPort());
    template = new RabbitTemplate(connectionFactory);
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceive() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    template.setRoutingKey(ROUTE);/* w w w  .j  a  v  a  2s .  c o  m*/
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceiveExternalExecutor() throws Exception {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
    final String execName = "make-sure-exec-passed-in";
    exec.setBeanName(execName);/*from  ww  w  . ja  v  a2 s  . c om*/
    exec.afterPropertiesSet();
    connectionFactory.setExecutor(exec);
    final Field[] fields = new Field[1];
    ReflectionUtils.doWithFields(RabbitTemplate.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            fields[0] = field;
        }
    }, new FieldFilter() {
        public boolean matches(Field field) {
            return field.getName().equals("logger");
        }
    });
    Log logger = Mockito.mock(Log.class);
    when(logger.isTraceEnabled()).thenReturn(true);

    final AtomicBoolean execConfiguredOk = new AtomicBoolean();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String log = (String) invocation.getArguments()[0];
            if (log.startsWith("Message received") && Thread.currentThread().getName().startsWith(execName)) {
                execConfiguredOk.set(true);
            }
            return null;
        }
    }).when(logger).trace(Mockito.anyString());
    final RabbitTemplate template = new RabbitTemplate(connectionFactory);
    ReflectionUtils.setField(fields[0], template, logger);
    template.setRoutingKey(ROUTE);
    template.setQueue(ROUTE);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;
            for (int i = 0; i < 10; i++) {
                message = template.receive();
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive();
    assertEquals(null, reply);

    assertTrue(execConfiguredOk.get());
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceiveWithRoutingKey() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;/*w  ww .  j a va2  s .  c  om*/
            for (int i = 0; i < 10; i++) {
                message = template.receive(ROUTE);
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive(ROUTE, message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive(ROUTE);
    assertEquals(null, reply);
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java

@Test
public void testAtomicSendAndReceiveWithExchangeAndRoutingKey() throws Exception {
    final RabbitTemplate template = new RabbitTemplate(new CachingConnectionFactory());
    ExecutorService executor = Executors.newFixedThreadPool(1);
    // Set up a consumer to respond to our producer
    Future<Message> received = executor.submit(new Callable<Message>() {

        public Message call() throws Exception {
            Message message = null;/*from   w  w  w .  j  av a2s  .c  om*/
            for (int i = 0; i < 10; i++) {
                message = template.receive(ROUTE);
                if (message != null) {
                    break;
                }
                Thread.sleep(100L);
            }
            assertNotNull("No message received", message);
            template.send(message.getMessageProperties().getReplyTo(), message);
            return message;
        }

    });
    Message message = new Message("test-message".getBytes(), new MessageProperties());
    Message reply = template.sendAndReceive("", ROUTE, message);
    assertEquals(new String(message.getBody()),
            new String(received.get(1000, TimeUnit.MILLISECONDS).getBody()));
    assertNotNull("Reply is expected", reply);
    assertEquals(new String(message.getBody()), new String(reply.getBody()));
    // Message was consumed so nothing left on queue
    reply = template.receive(ROUTE);
    assertEquals(null, reply);
}