Example usage for org.springframework.amqp.rabbit.core RabbitAdmin declareExchange

List of usage examples for org.springframework.amqp.rabbit.core RabbitAdmin declareExchange

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.core RabbitAdmin declareExchange.

Prototype

@Override
    public void declareExchange(final Exchange exchange) 

Source Link

Usage

From source file:com.mtech.easyexchange.ordersolver.OrderSolverConfigurer.java

public static void main(String... args) throws Exception {

    ConnectionFactory cf = new CachingConnectionFactory("127.0.0.1");

    RabbitAdmin admin = new RabbitAdmin(cf);

    Queue queue = new Queue("OrderQueue");
    admin.declareQueue(queue);// w w w.ja  v  a2 s.c o m

    TopicExchange exchange = new TopicExchange("OrderExchange");
    admin.declareExchange(exchange);

    admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("*"));

    OrderMessageHolder holder = new OrderMessageHolder();

    OrderSolverThread ost = new OrderSolverThread(holder);
    ost.start();

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
    container.setMessageListener(new OrderMessageConsumer(holder));
    container.setQueueNames("OrderQueue");
    container.start();
}

From source file:com.anton.dev.tqrbs2.basic.BasicJava.java

public static void main(String[] args) throws Exception {
    ConnectionFactory cf = new CachingConnectionFactory();

    // set up the queue, exchange, binding on the broker
    RabbitAdmin admin = new RabbitAdmin(cf);
    Queue queue = new Queue("myQueue");
    admin.declareQueue(queue);/*from www  .  j a  v a 2s . c o  m*/
    TopicExchange exchange = new TopicExchange("myExchange2");
    admin.declareExchange(exchange);
    admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("foo.*"));

    // set up the listener and container
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
    Object listener = new Object() {
        public void handleMessage(String foo) {
            LOGGER.info("Recibiendo Java: " + foo);
        }
    };
    MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
    container.setMessageListener(adapter);
    container.setQueueNames("myQueue");
    container.start();

    // send something
    RabbitTemplate template = new RabbitTemplate(cf);
    String msg = "Hello, world Rabbit!";
    LOGGER.info("Enviando Java: " + msg);
    template.convertAndSend("myExchange2", "foo.bar", msg);
    Thread.sleep(1000);
    container.stop();
}

From source file:com.xoom.rabbit.test.Main.java

public static void main(String[] args) throws InterruptedException {
    if (args.length != 9) {
        System.out.println(/*from   w w  w  .  j  av  a2s.  c o  m*/
                "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]");
        return;
    }
    final long startTime = System.currentTimeMillis();
    int consumerThreads = Integer.parseInt(args[0]);
    final int messages = Integer.parseInt(args[1]);
    String host = args[2];
    int port = Integer.parseInt(args[3]);
    boolean produce = Boolean.parseBoolean(args[4]);
    boolean consume = Boolean.parseBoolean(args[5]);
    final int messageSize = Integer.parseInt(args[6]);
    String username = args[7];
    String password = args[8];

    if (produce) {
        System.out.println("Sending " + messages + " messages to " + host + ":" + port);
    }
    if (consume) {
        System.out.println("Consuming " + messages + " messages from " + host + ":" + port);
    }
    if (!produce && !consume) {
        System.out.println("Not producing or consuming any messages.");
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setChannelCacheSize(consumerThreads + 1);

    RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    Queue queue = new Queue(QUEUE_NAME);
    amqpAdmin.declareExchange(exchange);
    amqpAdmin.declareQueue(queue);
    amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY));

    final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory);

    final CountDownLatch producerLatch = new CountDownLatch(messages);
    final CountDownLatch consumerLatch = new CountDownLatch(messages);

    SimpleMessageListenerContainer listenerContainer = null;

    if (consume) {
        listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setQueueNames(QUEUE_NAME);
        listenerContainer.setConcurrentConsumers(consumerThreads);
        listenerContainer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (consumerLatch.getCount() == 1) {
                    System.out.println("Finished consuming " + messages + " messages in "
                            + (System.currentTimeMillis() - startTime) + "ms");
                }
                consumerLatch.countDown();
            }
        });
        listenerContainer.start();
    }

    if (produce) {
        while (producerLatch.getCount() > 0) {
            try {
                byte[] message = new byte[messageSize];
                RND.nextBytes(message);
                amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties()));
                producerLatch.countDown();
            } catch (Exception e) {
                System.out.println("Failed to send message " + (messages - producerLatch.getCount())
                        + " will retry forever.");
            }
        }
    }

    if (consume) {
        consumerLatch.await();
        listenerContainer.shutdown();
    }

    connectionFactory.destroy();
}

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

/**
 * Maybe declare the exchange.//from  w w w. j a va2  s.  c o  m
 */
protected void maybeDeclareExchange() {
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    if (declareExchange) {
        Exchange x;
        if ("topic".equals(exchangeType)) {
            x = new TopicExchange(exchangeName, durable, autoDelete);
        } else if ("direct".equals(exchangeType)) {
            x = new DirectExchange(exchangeName, durable, autoDelete);
        } else if ("fanout".equals(exchangeType)) {
            x = new FanoutExchange(exchangeName, durable, autoDelete);
        } else if ("headers".equals(exchangeType)) {
            x = new HeadersExchange(exchangeType, durable, autoDelete);
        } else {
            x = new TopicExchange(exchangeName, durable, autoDelete);
        }
        admin.declareExchange(x);
    }
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java

@Test
public void testCleanStream() {
    final RabbitBindingCleaner cleaner = new RabbitBindingCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;//w  w w  .  j av a2  s .  c o  m
    CachingConnectionFactory connectionFactory = rabbitWithMgmtEnabled.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    for (int i = 0; i < 5; i++) {
        String queue1Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + i);
        String queue2Name = AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".default." + i);
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", AbstractBinder.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        TopicExchange exchange = new TopicExchange(queue1Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue1Name)).to(exchange).with(queue1Name));
        exchange = new TopicExchange(queue2Name);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(queue2Name)).to(exchange).with(queue2Name));
    }
    final TopicExchange topic1 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic1).with("#"));
    String foreignQueue = UUID.randomUUID().toString();
    rabbitAdmin.declareQueue(new Queue(foreignQueue));
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(foreignQueue)).to(topic1).with("#"));
    final TopicExchange topic2 = new TopicExchange(
            AbstractBinder.applyPrefix(BINDER_PREFIX, stream2 + ".foo.bar"));
    rabbitAdmin.declareExchange(topic2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(topic2).with("#"));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = AbstractBinder.applyPrefix(BINDER_PREFIX, stream1 + ".default." + 4);
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Queue " + queueName + " is in use");
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e).hasMessageContaining("Cannot delete exchange ");
                assertThat(e).hasMessageContaining("; it has bindings:");
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertThat(n < 100).withFailMessage("Consumer state remained at " + state + " after 10 seconds");
        }

    });
    rabbitAdmin.deleteExchange(topic1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(topic1);
    rabbitAdmin.deleteQueue(foreignQueue);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertThat(cleanedMap).hasSize(2);
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertThat(cleanedQueues).hasSize(10);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i * 2)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i);
        assertThat(cleanedQueues.get(i * 2 + 1)).isEqualTo(BINDER_PREFIX + stream1 + ".default." + i + ".dlq");
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertThat(cleanedMap).hasSize(2);
    cleanedQueues = cleanedMap.get("queues");
    assertThat(cleanedQueues).hasSize(5);
    for (int i = 0; i < 5; i++) {
        assertThat(cleanedQueues.get(i)).isEqualTo(BINDER_PREFIX + stream2 + ".default." + i);
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertThat(cleanedExchanges).hasSize(6);
}

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

@Test
public void testIgnoreDeclarationExeptionsTimeout() throws Exception {
    com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    TimeoutException toBeThrown = new TimeoutException("test");
    doThrow(toBeThrown).when(rabbitConnectionFactory).newConnection(any(ExecutorService.class), anyString());
    CachingConnectionFactory ccf = new CachingConnectionFactory(rabbitConnectionFactory);
    RabbitAdmin admin = new RabbitAdmin(ccf);
    List<DeclarationExceptionEvent> events = new ArrayList<DeclarationExceptionEvent>();
    admin.setApplicationEventPublisher(new EventPublisher(events));
    admin.setIgnoreDeclarationExceptions(true);
    admin.declareQueue(new AnonymousQueue());
    admin.declareQueue();/*from   w  w  w  .j  a  va  2s . c om*/
    admin.declareExchange(new DirectExchange("foo"));
    admin.declareBinding(new Binding("foo", DestinationType.QUEUE, "bar", "baz", null));
    assertThat(events.size(), equalTo(4));
    assertThat(events.get(0).getSource(), sameInstance(admin));
    assertThat(events.get(0).getDeclarable(), instanceOf(AnonymousQueue.class));
    assertSame(toBeThrown, events.get(0).getThrowable().getCause());
    assertNull(events.get(1).getDeclarable());
    assertSame(toBeThrown, events.get(1).getThrowable().getCause());
    assertThat(events.get(2).getDeclarable(), instanceOf(DirectExchange.class));
    assertSame(toBeThrown, events.get(2).getThrowable().getCause());
    assertThat(events.get(3).getDeclarable(), instanceOf(Binding.class));
    assertSame(toBeThrown, events.get(3).getThrowable().getCause());

    assertSame(events.get(3), admin.getLastDeclarationExceptionEvent());
}

From source file:org.springframework.amqp.rabbit.test.BrokerFederated.java

@SuppressWarnings("deprecation")
@Override/*from  www  .  j a  v a2 s. co  m*/
public Statement apply(Statement base, FrameworkMethod method, Object target) {

    // Check at the beginning, so this can be used as a static field
    if (assumeOnline) {
        Assume.assumeTrue(brokerOnline.get(port));
    } else {
        Assume.assumeTrue(brokerOffline.get(port));
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();

    try {

        connectionFactory.setPort(port);
        if (StringUtils.hasText(hostName)) {
            connectionFactory.setHost(hostName);
        }
        RabbitAdmin admin = new RabbitAdmin(connectionFactory);
        org.springframework.amqp.core.FederatedExchange exchange = new org.springframework.amqp.core.FederatedExchange(
                "fedDirectRuleTest");
        exchange.setBackingType("direct");
        exchange.setUpstreamSet("upstream-set");
        admin.declareExchange(exchange);
        admin.deleteExchange("fedDirectRuleTest");

        brokerOffline.put(port, false);

        if (!assumeOnline) {
            Assume.assumeTrue(brokerOffline.get(port));
        }

    } catch (Exception e) {
        logger.warn("Not executing tests because federated connectivity test failed", e);
        brokerOnline.put(port, false);
        if (assumeOnline) {
            Assume.assumeNoException(e);
        }
    } finally {
        connectionFactory.destroy();
    }

    return super.apply(base, method, target);

}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testConsumerPropertiesWithUserInfrastructureNoBind() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
    Queue queue = new Queue("propsUser1.infra");
    admin.declareQueue(queue);// www  .  j  ava2s .co  m
    DirectExchange exchange = new DirectExchange("propsUser1");
    admin.declareExchange(exchange);
    admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("foo"));

    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setDeclareExchange(false);
    properties.getExtension().setBindQueue(false);

    Binding<MessageChannel> consumerBinding = binder.bindConsumer("propsUser1", "infra",
            createBindableChannel("input", new BindingProperties()), properties);
    Lifecycle endpoint = extractEndpoint(consumerBinding);
    SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer",
            SimpleMessageListenerContainer.class);
    assertThat(container.isRunning()).isTrue();
    consumerBinding.unbind();
    assertThat(container.isRunning()).isFalse();
    RabbitManagementTemplate rmt = new RabbitManagementTemplate();
    List<org.springframework.amqp.core.Binding> bindings = rmt.getBindingsForExchange("/", exchange.getName());
    assertThat(bindings.size()).isEqualTo(1);
}