org.springframework.amqp.rabbit.core.RabbitTemplate Java Examples

The following examples show how to use org.springframework.amqp.rabbit.core.RabbitTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RabbitMQConfiguration.java    From seed with Apache License 2.0 6 votes vote down vote up
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(new Jackson2JsonMessageConverter());
    template.setEncoding(SeedConstants.DEFAULT_CHARSET);
    //消息发送失败时,返回到队列中(需要spring.rabbitmq.publisherReturns=true)
    template.setMandatory(true);
    //消息成功到达exchange,但没有queue与之绑定时触发的回调(即消息发送不到任何一个队列中)
    //也可以在生产者发送消息的类上实现org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback和RabbitTemplate.ReturnCallback两个接口(本例中即为SendController.java)
    template.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> LogUtil.getLogger().error("消息发送失败,replyCode={},replyText={},exchange={},routingKey={},消息体=[{}]", replyCode, replyText, exchange, routingKey, JSON.toJSONString(message.getBody())));
    //消息成功到达exchange后触发的ack回调(需要spring.rabbitmq.publisherConfirms=true)
    template.setConfirmCallback((correlationData, ack, cause) -> {
        if(ack){
            LogUtil.getLogger().info("消息发送成功,消息ID={}", correlationData.getId());
        }else{
            LogUtil.getLogger().error("消息发送失败,消息ID={},cause={}", correlationData.getId(), cause);
        }
    });
    return template;
}
 
Example #2
Source File: MQServer.java    From zxl with Apache License 2.0 6 votes vote down vote up
private void replyIfNecessary(Message message, Object result, RabbitTemplate mqTemplate) {
	MessageProperties messageProperties = message.getMessageProperties();
	String correlationId = null;
	try {
		correlationId = new String(messageProperties.getCorrelationId(), DEFAULT_CHARSET);
	} catch (Exception ignored) {
		try {
			correlationId = (String) SerializationUtils.deserialize(messageProperties.getCorrelationId());
		} catch (Exception warnException) {
			LogUtil.warn(logger, "#####获取correlationId失败,可能导致客户端挂起", warnException);
		}
	}
	boolean isNecessary = result != null && messageProperties.getReplyTo() != null;
	if (isNecessary) {
		mqTemplate.send(messageProperties.getReplyTo(), correlationId == null ? mqMessageConverter.toSendMessage(result) : mqMessageConverter.toReplyMessage(result, correlationId));
	}
}
 
Example #3
Source File: RabbitWithoutRabbitTemplateConfig.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void sendReplyIfRequested(Message message) {
  MessageProperties messageProperties = message.getMessageProperties();
  String replyToProperty = messageProperties.getReplyTo();

  if (replyToProperty != null) {
    RabbitTemplate rabbitTemplate = rabbitTemplateProvider.getRabbitTemplate();
    Address replyTo = new Address(replyToProperty);
    String replyMsg = REPLY_MSG_PREFIX + new String(message.getBody(), UTF_8);
    Message replyMessage = rabbitTemplate.getMessageConverter().toMessage(replyMsg, null);

    Object addCustomResponseErrorMarkerHeader = messageProperties.getHeaders()
        .get(HEADER_ADD_CUSTOM_ERROR_HEADER_TO_RESPONSE);

    if (addCustomResponseErrorMarkerHeader != null) {
      replyMessage.getMessageProperties().setHeader(HEADER_CUSTOM_RESPONSE_ERROR_MARKER_HEADER, "dummy error message");
    }
    replyMessage.getMessageProperties().setCorrelationId(messageProperties.getCorrelationId());

    rabbitTemplate.convertAndSend(replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage);
  }
}
 
Example #4
Source File: RabbitConfig.java    From SpringBootBucket with MIT License 6 votes vote down vote up
/**
 * 定制化amqp模版      可根据需要定制多个
 * <p>
 * <p>
 * 此处为模版类定义 Jackson消息转换器
 * ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调   即消息发送到exchange  ack
 * ReturnCallback接口用于实现消息发送到RabbitMQ 交换器,但无相应队列与交换器绑定时的回调  即消息发送不到任何一个队列中  ack
 *
 * @return the amqp template
 */
// @Primary
@Bean
public AmqpTemplate amqpTemplate() {
    Logger log = LoggerFactory.getLogger(RabbitTemplate.class);
    // 使用jackson 消息转换器
    rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    rabbitTemplate.setEncoding("UTF-8");
    // 消息发送失败返回到队列中,yml需要配置 publisher-returns: true
    rabbitTemplate.setMandatory(true);
    rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
        String correlationId = message.getMessageProperties().getCorrelationIdString();
        log.debug("消息:{} 发送失败, 应答码:{} 原因:{} 交换机: {}  路由键: {}", correlationId, replyCode, replyText, exchange, routingKey);
    });
    // 消息确认,yml需要配置 publisher-confirms: true
    rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
        if (ack) {
            log.debug("消息发送到exchange成功,id: {}", correlationData.getId());
        } else {
            log.debug("消息发送到exchange失败,原因: {}", cause);
        }
    });
    return rabbitTemplate;
}
 
Example #5
Source File: RabbitMQConfig.java    From rome with Apache License 2.0 5 votes vote down vote up
@Bean("rabbitTemplate")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory,
                                     @Qualifier("jackson2JsonMessageConverter") Jackson2JsonMessageConverter jackson2JsonMessageConverter) {
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.setMessageConverter(new Jackson2JsonMessageConverter());
    return template;
}
 
Example #6
Source File: AutoConfigureMessageVerifierTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConfigureForNoOpWhenMissingImplementation() {
	this.contextRunner
			.withClassLoader(new FilteredClassLoader(org.apache.camel.Message.class,
					org.springframework.messaging.Message.class, JmsTemplate.class,
					KafkaTemplate.class, RabbitTemplate.class, EnableBinding.class))
			.run((context) -> {
				assertThat(context.getBeansOfType(MessageVerifierSender.class))
						.hasSize(1);
				assertThat(context.getBeansOfType(NoOpStubMessages.class)).hasSize(1);
			});
}
 
Example #7
Source File: AmqpConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(AmqpMessageDispatcherService.class)
AmqpMessageDispatcherService amqpMessageDispatcherService(final RabbitTemplate rabbitTemplate,
        final AmqpMessageSenderService amqpSenderService, final ArtifactUrlHandler artifactUrlHandler,
        final SystemSecurityContext systemSecurityContext, final SystemManagement systemManagement,
        final TargetManagement targetManagement, final DistributionSetManagement distributionSetManagement,
        final SoftwareModuleManagement softwareModuleManagement, final DeploymentManagement deploymentManagement) {
    return new AmqpMessageDispatcherService(rabbitTemplate, amqpSenderService, artifactUrlHandler,
            systemSecurityContext, systemManagement, targetManagement, serviceMatcher, distributionSetManagement,
            softwareModuleManagement, deploymentManagement);
}
 
Example #8
Source File: AmqpTestConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #9
Source File: AmqpConfig.java    From demo_springboot_rabbitmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(this.connectionFactory());
    template.setMessageConverter(this.jsonMessageConverter());
    template.setMandatory(true);
    return template;
}
 
Example #10
Source File: SpringAmqpStubMessages.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Autowired
public SpringAmqpStubMessages(RabbitTemplate rabbitTemplate,
		MessageListenerAccessor messageListenerAccessor,
		RabbitProperties rabbitProperties) {
	Assert.notNull(rabbitTemplate, "RabbitTemplate must be set");
	Assert.isTrue(
			mockingDetails(rabbitTemplate).isSpy()
					|| mockingDetails(rabbitTemplate).isMock(),
			"StubRunner AMQP will work only if RabbiTemplate is a spy");
	this.rabbitTemplate = rabbitTemplate;
	this.messageListenerAccessor = messageListenerAccessor;
	this.rabbitProperties = rabbitProperties;
}
 
Example #11
Source File: RabbitTemplateConfig.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    return template;
}
 
Example #12
Source File: Issue178ListenerConfiguration.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Bean
SimpleMessageListenerContainer messageListenerContainer(
		ConnectionFactory connectionFactory, RabbitTemplate rabbitTemplate) {
	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
	container.setConnectionFactory(connectionFactory);
	container.addQueueNames("rated-item-service.rated-item-event.exchange");
	container.setMessageListener(exampleListener(rabbitTemplate));
	return container;
}
 
Example #13
Source File: PublishTraceLog.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public PublishTraceLog(final RabbitTemplate rabbitTemplate, final Channel channel, final String exchange,
    final String routingKey, final Message message, final boolean mandatory,
    final CorrelationData correlationData) {
    this.rabbitTemplate = rabbitTemplate;
    this.channel = channel;
    this.exchange = exchange;
    this.routingKey = routingKey;
    this.message = message;
    this.mandatory = mandatory;
    this.correlationData = correlationData;
}
 
Example #14
Source File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 5 votes vote down vote up
@Bean
RabbitTemplate rabbitTemplate(org.springframework.amqp.rabbit.connection.ConnectionFactory  cf,
                              ObjectMapper mapper) {
    RabbitTemplate template = new RabbitTemplate(cf);
    template.setExchange(EXCHANGE_NAME);
    RetryTemplate retry = new RetryTemplate();
    ExponentialBackOffPolicy backOff = new ExponentialBackOffPolicy();
    backOff.setInitialInterval(1000);
    backOff.setMultiplier(1.5);
    backOff.setMaxInterval(60000);
    retry.setBackOffPolicy(backOff);
    template.setRetryTemplate(retry);
    template.setMessageConverter(new Jackson2JsonMessageConverter(mapper));
    return template;
}
 
Example #15
Source File: AmqpConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create AMQP handler service bean for authentication messages.
 * 
 * @return handler service bean
 */
@Bean
AmqpAuthenticationMessageHandler amqpAuthenticationMessageHandler(final RabbitTemplate rabbitTemplate,
        final AmqpControllerAuthentication authenticationManager, final ArtifactManagement artifactManagement,
        final DownloadIdCache downloadIdCache, final HostnameResolver hostnameResolver,
        final ControllerManagement controllerManagement, final TenantAware tenantAware) {
    return new AmqpAuthenticationMessageHandler(rabbitTemplate, authenticationManager, artifactManagement,
            downloadIdCache, hostnameResolver, controllerManagement, tenantAware);
}
 
Example #16
Source File: RabbitConfig.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    return template;
}
 
Example #17
Source File: SpringRabbitTracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void decorateRabbitTemplate_appends_when_absent() {
  RabbitTemplate template = new RabbitTemplate();
  template.setBeforePublishPostProcessors(new UnzipPostProcessor());

  assertThat(rabbitTracing.decorateRabbitTemplate(template))
    .extracting("beforePublishPostProcessors")
    .satisfies(postProcessors -> assertThat(((Collection) postProcessors)).anyMatch(
      postProcessor -> postProcessor instanceof TracingMessagePostProcessor
    ));
}
 
Example #18
Source File: RabbitTemplateMessageQueueFactory.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
public RabbitTemplateMessageQueueFactory(
        String elasticActorsCluster,
        AmqpAdmin amqpAdmin,
        RabbitTemplate rabbitTemplate) {
    this.elasticActorsCluster = elasticActorsCluster;
    this.amqpAdmin = amqpAdmin;
    this.rabbitTemplate = rabbitTemplate;
    this.exchangeName = String.format(EA_EXCHANGE_FORMAT, elasticActorsCluster);
}
 
Example #19
Source File: RabbitBlockchainEventBroadcasterTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
    rabbitTemplate = Mockito.mock(RabbitTemplate.class);
    rabbitSettings = Mockito.mock(RabbitSettings.class);

    Mockito.when(rabbitSettings.getExchange()).thenReturn(EVENT_EXCHANGE);
    Mockito.when(rabbitSettings.getBlockEventsRoutingKey()).thenReturn(NEW_BLOCK_ROUTING_KEY);
    Mockito.when(rabbitSettings.getContractEventsRoutingKey()).thenReturn(CONTRACT_EVENT_ROUTING_KEY);
    Mockito.when(rabbitSettings.getTransactionEventsRoutingKey()).thenReturn(TRANSACTION_EVENT_ROUTING_KEY);

    underTest = new RabbitBlockChainEventBroadcaster(rabbitTemplate, rabbitSettings);
}
 
Example #20
Source File: SpringRabbitTracingTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void decorateRabbitTemplate_adds_by_default() {
  RabbitTemplate template = new RabbitTemplate();
  assertThat(rabbitTracing.decorateRabbitTemplate(template))
    .extracting("beforePublishPostProcessors")
    .satisfies(postProcessors -> assertThat(((Collection) postProcessors)).anyMatch(
      postProcessor -> postProcessor instanceof TracingMessagePostProcessor
    ));
}
 
Example #21
Source File: SpringIntegrationTest.java    From rabbitmq-mock with Apache License 2.0 5 votes vote down vote up
@Test
void basic_consume_case() {
    String messageBody = "Hello world!";
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AmqpConfiguration.class)) {
        RabbitTemplate rabbitTemplate = queueAndExchangeSetup(context);

        Receiver receiver = new Receiver();
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(context.getBean(ConnectionFactory.class));
        container.setQueueNames(QUEUE_NAME);
        container.setMessageListener(new MessageListenerAdapter(receiver, "receiveMessage"));
        try {
            container.start();

            rabbitTemplate.convertAndSend(EXCHANGE_NAME, "test.key2", messageBody);

            List<String> receivedMessages = new ArrayList<>();
            assertTimeoutPreemptively(ofMillis(500L), () -> {
                    while (receivedMessages.isEmpty()) {
                        receivedMessages.addAll(receiver.getMessages());
                        TimeUnit.MILLISECONDS.sleep(100L);
                    }
                }
            );

            assertThat(receivedMessages).containsExactly(messageBody);
        } finally {
            container.stop();
        }
    }
}
 
Example #22
Source File: RabbitMqSendTracingAspect.java    From java-spring-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @see RabbitTemplate#convertSendAndReceive(String, String, Object, MessagePostProcessor, CorrelationData)
 */
@Around(value = "execution(* org.springframework.amqp.rabbit.core.RabbitTemplate.convertSendAndReceive(..)) " +
                "&& args(exchange, routingKey, message, messagePostProcessor, correlationData)",
    argNames = "pjp,exchange,routingKey,message,messagePostProcessor,correlationData")
public Object traceRabbitConvertSendAndReceive(
    ProceedingJoinPoint pjp, String exchange, String routingKey, Object message,
    MessagePostProcessor messagePostProcessor, CorrelationData correlationData)
    throws Throwable {
  return createTracingHelper()
      .nullResponseMeansTimeout((RabbitTemplate) pjp.getTarget())
      .doWithTracingHeadersMessage(exchange, routingKey, message, (convertedMessage) ->
          proceedReplacingMessage(pjp, convertedMessage, 2));
}
 
Example #23
Source File: ITSpringRabbit.java    From brave with Apache License 2.0 5 votes vote down vote up
@Bean RabbitTemplate decorateRabbitTemplate(
  ConnectionFactory connectionFactory,
  Binding binding,
  SpringRabbitTracing springRabbitTracing
) {
  RabbitTemplate result = new RabbitTemplate(connectionFactory);
  result.setExchange(binding.getExchange());
  return springRabbitTracing.decorateRabbitTemplate(result);
}
 
Example #24
Source File: RabbitTemplateConfig.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    return template;
}
 
Example #25
Source File: ITSpringRabbit.java    From brave with Apache License 2.0 5 votes vote down vote up
@Bean RabbitTemplate newRabbitTemplate(
  ConnectionFactory connectionFactory,
  Binding binding,
  SpringRabbitTracing springRabbitTracing
) {
  RabbitTemplate result = springRabbitTracing.newRabbitTemplate(connectionFactory);
  result.setExchange(binding.getExchange());
  return result;
}
 
Example #26
Source File: RabbitConfiguration.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
@Bean
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setMessageConverter(messageConverter());
    return template;
}
 
Example #27
Source File: Sender.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public Sender(RabbitTemplate rabbitTemplate, Queue candidateQueue) {
	this.rabbitTemplate = rabbitTemplate;
	this.candidateQueue = candidateQueue;
}
 
Example #28
Source File: SpringIntegrationTest.java    From rabbitmq-mock with Apache License 2.0 4 votes vote down vote up
@Bean
RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    return new RabbitTemplate(connectionFactory);
}
 
Example #29
Source File: RabbitMQConfigAsync.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Bean
public RabbitTemplate template() {
	RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory);
	rabbitTemplate.setRoutingKey("msg.request");
	return rabbitTemplate;
}
 
Example #30
Source File: SendRequestEventLogin.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
public SendRequestEventLogin(Queue queue, RabbitTemplate rabbitTemplate) {
	this.rabbitTemplate = rabbitTemplate;
	this.queue = queue;
}