List of usage examples for org.springframework.amqp.rabbit.core RabbitTemplate send
@Override public void send(final String exchange, final String routingKey, final Message message) throws AmqpException
From source file:com.jbrisbin.vpc.jobsched.RequeueJob.java
public void maybeRequeue() { RequestMeta meta = new RequestMeta(); meta.setQueryParam("keys", "true"); BucketResponse bucket = riak.listBucket(riakBucket, meta); if (bucket.isSuccess()) { for (String messageId : bucket.getBucketInfo().getKeys()) { FetchResponse response = riak.fetch(riakBucket, messageId); if (response.isSuccess()) { // Try re-queueing message try { if (log.isDebugEnabled()) { log.debug("Requeueing messageId: " + messageId); }// ww w . j a v a2 s . c o m final Map<String, Object> message = mapper.readValue(response.getBodyAsString(), Map.class); RabbitTemplate tmpl = appCtx.getBean(RabbitTemplate.class); final MessageProperties props = new RabbitMessageProperties(); Map headers = (Map) message.get("headers"); for (Object key : headers.keySet()) { props.setHeader(key.toString(), headers.get(key)); } props.setCorrelationId(messageId.getBytes()); props.setContentType("application/json"); tmpl.send(message.get("exchange").toString(), message.get("route").toString(), new MessageCreator() { @Override public Message createMessage() { Message msg = new Message(message.get("body").toString().getBytes(), props); if (log.isDebugEnabled()) { log.debug("Sending AMQP message: " + msg.toString()); } return msg; } }); // Delete from nosql store if (log.isDebugEnabled()) { log.debug("Deleting messageId " + messageId + " from requeue cache"); } riak.delete(riakBucket, messageId); } catch (IOException e) { log.error(e.getMessage(), e); } } } } }
From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java
@Test public void testDebatchByContainerBadMessageRejected() throws Exception { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory); container.setQueueNames(ROUTE);// w w w . j a va2 s .c om container.setMessageListener((MessageListener) message -> { }); container.setReceiveTimeout(100); ConditionalRejectingErrorHandler errorHandler = new ConditionalRejectingErrorHandler(); container.setErrorHandler(errorHandler); container.afterPropertiesSet(); container.start(); Log logger = spy(TestUtils.getPropertyValue(errorHandler, "logger", Log.class)); doReturn(true).when(logger).isWarnEnabled(); doAnswer(new DoesNothing()).when(logger).warn(anyString(), any(Throwable.class)); new DirectFieldAccessor(errorHandler).setPropertyValue("logger", logger); try { RabbitTemplate template = new RabbitTemplate(); template.setConnectionFactory(this.connectionFactory); MessageProperties props = new MessageProperties(); props.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT, MessageProperties.BATCH_FORMAT_LENGTH_HEADER4); Message message = new Message("\u0000\u0000\u0000\u0004foo".getBytes(), props); template.send("", ROUTE, message); Thread.sleep(1000); ArgumentCaptor<Object> arg1 = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<Throwable> arg2 = ArgumentCaptor.forClass(Throwable.class); verify(logger).warn(arg1.capture(), arg2.capture()); assertThat(arg2.getValue().getMessage(), containsString("Bad batched message received")); } finally { container.stop(); } }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerWithRabbitMQ.java
public static void main(String[] args) throws InterruptedException { CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost"); connectionFactory.setHost("localhost"); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); assertNotNull(connectionFactory);/*ww w . ja v a2 s .co m*/ MessageConverter messageConverter = new SimpleMessageConverter(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames("foo"); container.setPrefetchCount(1000); container.setTxSize(500); container.setAcknowledgeMode(AcknowledgeMode.AUTO); container.setConcurrentConsumers(20); container.setMessageListener(new MessageListenerAdapter(new SimpleAdapter(), messageConverter)); container.start(); RabbitTemplate template = new RabbitTemplate(connectionFactory); template.setMessageConverter(messageConverter); List<BlockingQueue<?>> queues = getQueues(container); Thread.sleep(10000); int n = 0; while (true) { for (int i = 1; i <= 200; i++) { template.send("foo", "", new Message( "foo # ID: id".replace("#", String.valueOf(i)) .replace("id", java.util.UUID.randomUUID().toString()).getBytes(), messageProperties)); } Thread.sleep(1000); if (++n % 10 == 0) { logger.warn(count(queues)); } } }
From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java
@SuppressWarnings("rawtypes") @Test//from www.ja v a2s.com public void testWithId() throws Exception { // 2 messages; each retried twice by retry interceptor this.latch = new CountDownLatch(6); ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml", this.getClass()); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setMessageListener(new MessageListenerAdapter(new POJO())); container.setQueueNames("retry.test.queue"); StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean(); // use an external template so we can share his cache RetryTemplate retryTemplate = new RetryTemplate(); RetryContextCache cache = spy(new MapRetryContextCache()); retryTemplate.setRetryContextCache(cache); fb.setRetryOperations(retryTemplate); fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer()); Advice retryInterceptor = fb.getObject(); container.setAdviceChain(retryInterceptor); container.start(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); messageProperties.setMessageId("foo"); Message message = new Message("Hello, world!".getBytes(), messageProperties); template.send("retry.test.exchange", "retry.test.binding", message); template.send("retry.test.exchange", "retry.test.binding", message); try { assertTrue(latch.await(30, TimeUnit.SECONDS)); Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map"); int n = 0; while (n++ < 100 && map.size() != 0) { Thread.sleep(100); } ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class); verify(cache, times(6)).put(putCaptor.capture(), any(RetryContext.class)); verify(cache, times(6)).get(getCaptor.capture()); verify(cache, atLeast(2)).remove(removeCaptor.capture()); verify(cache, atMost(4)).remove(removeCaptor.capture()); logger.debug("puts:" + putCaptor.getAllValues()); logger.debug("gets:" + putCaptor.getAllValues()); logger.debug("removes:" + removeCaptor.getAllValues()); assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size()); } finally { container.stop(); ctx.close(); } }
From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java
@SuppressWarnings("rawtypes") @Test//from ww w. j a va2 s . c om public void testWithIdAndSuccess() throws Exception { // 2 messages; each retried twice by retry interceptor this.latch = new CountDownLatch(6); ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml", this.getClass()); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); final Set<String> processed = new HashSet<>(); final CountDownLatch latch = new CountDownLatch(4); container.setMessageListener(m -> { latch.countDown(); if (!processed.contains(m.getMessageProperties().getMessageId())) { processed.add(m.getMessageProperties().getMessageId()); throw new RuntimeException("fail"); } }); container.setQueueNames("retry.test.queue"); StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean(); // use an external template so we can share his cache RetryTemplate retryTemplate = new RetryTemplate(); RetryContextCache cache = spy(new MapRetryContextCache()); retryTemplate.setRetryContextCache(cache); fb.setRetryOperations(retryTemplate); fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer()); Advice retryInterceptor = fb.getObject(); container.setAdviceChain(retryInterceptor); container.start(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); messageProperties.setMessageId("foo"); Message message = new Message("Hello, world!".getBytes(), messageProperties); template.send("retry.test.exchange", "retry.test.binding", message); messageProperties.setMessageId("bar"); template.send("retry.test.exchange", "retry.test.binding", message); try { assertTrue(latch.await(30, TimeUnit.SECONDS)); Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map"); int n = 0; while (n++ < 100 && map.size() != 0) { Thread.sleep(100); } ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class); verify(cache, times(2)).put(putCaptor.capture(), any(RetryContext.class)); verify(cache, times(2)).get(getCaptor.capture()); verify(cache, atLeast(2)).remove(removeCaptor.capture()); verify(cache, atMost(4)).remove(removeCaptor.capture()); logger.debug("puts:" + putCaptor.getAllValues()); logger.debug("gets:" + putCaptor.getAllValues()); logger.debug("removes:" + removeCaptor.getAllValues()); assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size()); } finally { container.stop(); ctx.close(); } }