/** * 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()); }
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); }
@Override protected void endpointInit() { if (getConfirmCorrelationExpression() != null) { Assert.isInstanceOf(RabbitTemplate.class, this.amqpTemplate, "RabbitTemplate implementation is required for publisher confirms"); ((RabbitTemplate) this.amqpTemplate).setConfirmCallback(this); } if (getReturnChannel() != null) { Assert.isInstanceOf(RabbitTemplate.class, this.amqpTemplate, "RabbitTemplate implementation is required for publisher confirms"); ((RabbitTemplate) this.amqpTemplate).setReturnCallback(this); } }
/** * Set to true to enable publisher confirms. When enabled, the {@link RabbitFuture} * returned by the send and receive operation will have a * {@code ListenableFuture<Boolean>} in its {@code confirm} property. * @param enableConfirms true to enable publisher confirms. */ public void setEnableConfirms(boolean enableConfirms) { this.enableConfirms = enableConfirms; if (enableConfirms) { this.template.setConfirmCallback(this); } }
/** * Set to true to enable publisher confirms. When enabled, the {@link RabbitFuture} * returned by the send and receive operation will have a * {@code ListenableFuture<Boolean>} in its {@code confirm} property. * @param enableConfirms true to enable publisher confirms. */ public void setEnableConfirms(boolean enableConfirms) { this.enableConfirms = enableConfirms; if (enableConfirms) { this.template.setConfirmCallback(this); } }
@Autowired public Sender(RabbitTemplate rabbitTemplate) { this.rabbitTemplate = rabbitTemplate; this.rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话,那回调就是最后设置的内容 }
public void send(String message) { rabbitTemplate.setConfirmCallback(this); CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString()); rabbitTemplate.convertAndSend("seckillExchange", "seckillRoutingKey", message, correlationData); }
public void sendMessage(String context) { // 消息发送失败返回到队列中, application.properties 配置 spring.rabbitmq.publisher-returns=true rabbitTemplate.setMandatory(true); this.rabbitTemplate.setReturnCallback(this); this.rabbitTemplate.setConfirmCallback(this); this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { if (!ack) { logger.info("HelloSender 发送失败:" + cause + correlationData.toString()); } else { logger.info("HelloSender 发送成功"); } }); logger.info("HelloSender 发送的消息内容:{}", context); this.rabbitTemplate.convertAndSend("hello", context); }
@Override protected void endpointInit() { if (getConfirmCorrelationExpression() != null) { Assert.isInstanceOf(RabbitTemplate.class, this.amqpTemplate, "RabbitTemplate implementation is required for publisher confirms"); ((RabbitTemplate) this.amqpTemplate).setConfirmCallback(this); } if (getReturnChannel() != null) { Assert.isInstanceOf(RabbitTemplate.class, this.amqpTemplate, "RabbitTemplate implementation is required for publisher confirms"); ((RabbitTemplate) this.amqpTemplate).setReturnCallback(this); } }
public void send() { String context = "你好现在是 " + new Date() +""; System.out.println("HelloSender发送内容 : " + context); // this.rabbitTemplate.setConfirmCallback(this); this.rabbitTemplate.setReturnCallback(this); //为保证数据一致性,应先将数据保存到数据库当中 this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { if (!ack) { //先尝试重发机制 System.out.println("HelloSender消息发送失败" + cause + correlationData.toString()); } else { System.out.println("HelloSender 消息发送成功 "); } }); this.rabbitTemplate.convertAndSend("hello", context); }
@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 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 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("消息丢失: message({}),replyCode({}),replytext({}),exchange({}),routingKey({})",message,replyCode,replyText,exchange,routingKey)); return rabbitTemplate; }
private void setupCallbacks() { /* * Confirms/returns enabled in application.properties - add the callbacks here. */ this.rabbitTemplate.setConfirmCallback((correlation, ack, reason) -> { if (correlation != null) { System.out.println("Received " + (ack ? " ack " : " nack ") + "for correlation: " + correlation); } this.confirmLatch.countDown(); }); this.rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> { System.out.println("Returned: " + message + "\nreplyCode: " + replyCode + "\nreplyText: " + replyText + "\nexchange/rk: " + exchange + "/" + routingKey); this.returnLatch.countDown(); }); /* * Replace the correlation data with one containing the converted message in case * we want to resend it after a nack. */ this.rabbitTemplate.setCorrelationDataPostProcessor((message, correlationData) -> new CompleteMessageCorrelationData(correlationData != null ? correlationData.getId() : null, message)); }
public void sendOrder(TOrder order){ rabbitTemplate.setConfirmCallback(confirmCallback); CorrelationData correlationData = new CorrelationData(); correlationData.setId(order.getMessageId()); rabbitTemplate.convertAndSend("order-exchange","order.abcd",order,correlationData); } }
/** * @return {@link RabbitTemplate} with automatic retry, published confirms * and {@link Jackson2JsonMessageConverter}. */ @Bean public RabbitTemplate rabbitTemplate() { final RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); final RetryTemplate retryTemplate = new RetryTemplate(); retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy()); rabbitTemplate.setRetryTemplate(retryTemplate); rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { if (ack) { LOGGER.debug("Message with {} confirmed by broker.", correlationData); } else { LOGGER.error("Broker is unable to handle message with {} : {}", correlationData, cause); } }); return rabbitTemplate; }
@Test public void testConfirmReceivedAfterPublisherCallbackChannelScheduleClose() throws Exception { final CountDownLatch latch = new CountDownLatch(40); templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> latch.countDown()); ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 20; i++) { executorService.execute(() -> { templateWithConfirmsEnabled.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); templateWithConfirmsEnabled.convertAndSend("BAD_ROUTE", (Object) "bad", new CorrelationData("cba")); }); } assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1)); }
@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 testPublisherConfirmNotReceived() throws Exception { ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); Connection mockConnection = mock(Connection.class); Channel mockChannel = mock(Channel.class); when(mockChannel.isOpen()).thenReturn(true); when(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).thenReturn(mockConnection); when(mockConnection.isOpen()).thenReturn(true); doReturn(new PublisherCallbackChannelImpl(mockChannel, this.executorService)) .when(mockConnection) .createChannel(); CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory); ccf.setExecutor(mock(ExecutorService.class)); ccf.setPublisherConfirms(true); final RabbitTemplate template = new RabbitTemplate(ccf); final AtomicBoolean confirmed = new AtomicBoolean(); template.setConfirmCallback((correlationData, ack, cause) -> confirmed.set(true)); template.convertAndSend(ROUTE, (Object) "message", new CorrelationData("abc")); Thread.sleep(5); assertEquals(1, template.getUnconfirmedCount()); Collection<CorrelationData> unconfirmed = template.getUnconfirmed(-1); assertEquals(0, template.getUnconfirmedCount()); assertEquals(1, unconfirmed.size()); assertEquals("abc", unconfirmed.iterator().next().getId()); assertFalse(confirmed.get()); }
@Test public void testPublisherConfirmWithSendAndReceive() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<CorrelationData> confirmCD = new AtomicReference<CorrelationData>(); templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> { confirmCD.set(correlationData); latch.countDown(); }); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactoryWithConfirmsEnabled); container.setQueueNames(ROUTE); container.setMessageListener( new MessageListenerAdapter((ReplyingMessageListener<String, String>) String::toUpperCase)); container.start(); CorrelationData correlationData = new CorrelationData("abc"); String result = (String) this.templateWithConfirmsEnabled.convertSendAndReceive(ROUTE, (Object) "message", correlationData); container.stop(); assertEquals("MESSAGE", result); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(correlationData, confirmCD.get()); }