@Override public void run(String... args) throws Exception { System.out.println("Sending message..."); rabbitTemplate.convertAndSend(Application.topicExchangeName, "foo.bar.baz", "Hello from RabbitMQ!"); receiver.getLatch().await(10000, TimeUnit.MILLISECONDS); }
/** * 站内信 * @param mm */ public void sendMessage(MiaoshaMessage mm) { // String msg = RedisService.beanToString(mm); log.info("send message:"+"11111"); rabbitTemplate.convertAndSend(MQConfig.EXCHANGE_TOPIC,"miaosha_*", "111111111"); }
/** Creates an instrumented {@linkplain RabbitTemplate} */ public RabbitTemplate newRabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); TracingMessagePostProcessor tracingMessagePostProcessor = new TracingMessagePostProcessor(this); rabbitTemplate.setBeforePublishPostProcessors(tracingMessagePostProcessor); return rabbitTemplate; }
/** * the basic.return is sent to the client before basic.ack */ @PostConstruct public void postConstruct() { // return rabbitTemplate.setReturnCallback(new RabbitReturnCallback()); // ack rabbitTemplate.setConfirmCallback(new RabbitConfirmCallback()); }
@Before public void setUp() { this.rabbitTemplate = new RabbitTemplate(new CachingConnectionFactory("localhost")); this.rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); }
@Bean public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) { connectionFactory.setPublisherConfirms(true); connectionFactory.setPublisherReturns(true); RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMandatory(true); rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause)); rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message)); return rabbitTemplate; }
@Bean @Primary public RabbitTemplate rabbitTemplateForTest(final ConnectionFactory connectionFactory) { final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); rabbitTemplate.setReplyTimeout(TimeUnit.SECONDS.toMillis(3)); rabbitTemplate.setReceiveTimeout(TimeUnit.SECONDS.toMillis(3)); return rabbitTemplate; }
private RabbitTemplate createRabbitTemplate(MessageConverter messageConverter, RetryTemplate retryTemplate) { RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory); template.setMessageConverter(messageConverter); template.setRetryTemplate(retryTemplate); return template; }
public void send() { rabbitTemplatenew.setConfirmCallback(this); String msg="callbackSender : i am callback sender"; System.out.println(msg ); CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString()); System.out.println("callbackSender UUID: " + correlationData.getId()); this.rabbitTemplatenew.convertAndSend("exchange", "topic.messages", msg, correlationData); }
@Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //必须是prototype类型 public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; }
@Test public void testPublisherConfirmReceivedTwoTemplates() throws Exception { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> latch1.countDown()); templateWithConfirmsEnabled.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); RabbitTemplate secondTemplate = new RabbitTemplate(connectionFactoryWithConfirmsEnabled); secondTemplate.setConfirmCallback((correlationData, ack, cause) -> latch2.countDown()); secondTemplate.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def")); assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertTrue(latch2.await(10, TimeUnit.SECONDS)); assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1)); assertNull(secondTemplate.getUnconfirmed(-1)); }
@Test public void testSendAndReceiveTransactedWithUncachedConnection() throws Exception { final SingleConnectionFactory singleConnectionFactory = new SingleConnectionFactory("localhost"); RabbitTemplate template = new RabbitTemplate(singleConnectionFactory); template.setChannelTransacted(true); template.convertAndSend(ROUTE, "message"); String result = (String) template.receiveAndConvert(ROUTE); assertEquals("message", result); result = (String) template.receiveAndConvert(ROUTE); assertEquals(null, result); singleConnectionFactory.destroy(); }
@Test public void testConnect() throws Exception { RabbitAdmin admin = new RabbitAdmin(this.lqcf); Queue queue = new Queue(UUID.randomUUID().toString(), false, false, true); admin.declareQueue(queue); ConnectionFactory targetConnectionFactory = this.lqcf.getTargetConnectionFactory("[" + queue.getName() + "]"); RabbitTemplate template = new RabbitTemplate(targetConnectionFactory); template.convertAndSend("", queue.getName(), "foo"); assertEquals("foo", template.receiveAndConvert(queue.getName())); admin.deleteQueue(queue.getName()); }
@Test @DirtiesContext public void simpleEndpointWithSendTo() throws InterruptedException { rabbitTemplate.convertAndSend("test.sendTo", "bar"); rabbitTemplate.setReceiveTimeout(10000); Object result = rabbitTemplate.receiveAndConvert("test.sendTo.reply"); assertNotNull(result); assertEquals("BAR", result); }
})); RabbitTemplate rabbitTemplate = spy(new RabbitTemplate()); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); return null; }).when(rabbitTemplate) .send(anyString(), anyString(), any(org.springframework.amqp.core.Message.class), isNull());
@Bean public RabbitTemplate template() { RabbitTemplate rabbitTemplate = new RabbitTemplate(cf()); rabbitTemplate.setRoutingKey(TEST_QUEUE); rabbitTemplate.setDefaultReceiveQueue(TEST_QUEUE2); rabbitTemplate.setMessageConverter(jsonMessageConverter()); return rabbitTemplate; }
@Test public void testReceiveInTransaction() throws Exception { template.convertAndSend(ROUTE, "message"); String result = transactionTemplate.execute(status -> (String) template.receiveAndConvert(ROUTE)); assertEquals("message", result); result = (String) template.receiveAndConvert(ROUTE); assertEquals(null, result); }
@Test public void testDelayExpression() { ConnectionFactory connectionFactory = mock(ConnectionFactory.class); RabbitTemplate amqpTemplate = spy(new RabbitTemplate(connectionFactory)); AmqpOutboundEndpoint endpoint = new AmqpOutboundEndpoint(amqpTemplate); willDoNothing() .given(amqpTemplate).send(anyString(), anyString(), any(Message.class), isNull()); willAnswer(invocation -> invocation.getArgument(2)) .given(amqpTemplate) .sendAndReceive(anyString(), anyString(), any(Message.class), isNull()); endpoint.setExchangeName("foo"); endpoint.setRoutingKey("bar"); endpoint.handleMessage(new GenericMessage<>("foo")); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(amqpTemplate).send(eq("foo"), eq("bar"), captor.capture(), isNull()); assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(42)); endpoint.setExpectReply(true); endpoint.setOutputChannel(new NullChannel()); endpoint.handleMessage(new GenericMessage<>("foo")); verify(amqpTemplate).sendAndReceive(eq("foo"), eq("bar"), captor.capture(), isNull()); assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(42)); endpoint.afterPropertiesSet(); endpoint.handleMessage(new GenericMessage<>("foo")); verify(amqpTemplate).sendAndReceive(eq("foo"), eq("baz"), captor.capture(), isNull()); assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(23));
@Test public void testInt3430FailForNotLazyConnect() { RabbitTemplate amqpTemplate = spy(new RabbitTemplate()); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); RuntimeException toBeThrown = new RuntimeException("Test Connection Exception"); doThrow(toBeThrown).when(connectionFactory).createConnection(); when(amqpTemplate.getConnectionFactory()).thenReturn(connectionFactory); AmqpOutboundEndpoint handler = new AmqpOutboundEndpoint(amqpTemplate); Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.class)); new DirectFieldAccessor(handler).setPropertyValue("logger", logger); doNothing().when(logger).error("Failed to eagerly establish the connection.", toBeThrown); ApplicationContext context = mock(ApplicationContext.class); handler.setApplicationContext(context); handler.setBeanFactory(context); handler.afterPropertiesSet(); handler.start(); handler.stop(); verify(logger, never()).error(anyString(), any(RuntimeException.class)); handler.setLazyConnect(false); handler.start(); verify(logger).error("Failed to eagerly establish the connection.", toBeThrown); handler.stop(); }
/** * Specify the {@link MessageConverter} to convert request and reply to/from {@link Message}. * If the {@link #amqpTemplate} is explicitly set, this {@link MessageConverter} * isn't populated there. You must configure that external {@link #amqpTemplate}. * @param messageConverter the {@link MessageConverter} to use. */ public void setMessageConverter(MessageConverter messageConverter) { Assert.notNull(messageConverter, "MessageConverter must not be null"); this.amqpMessageConverter = messageConverter; if (!this.amqpTemplateExplicitlySet) { ((RabbitTemplate) this.amqpTemplate).setMessageConverter(messageConverter); } }