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

The following examples show how to use org.springframework.amqp.rabbit.core.RabbitTemplate. These examples are extracted from open source projects. 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
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 2
Source Project: zxl   Source File: MQServer.java    License: 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 Project: SpringBootBucket   Source File: RabbitConfig.java    License: 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 4
Source Project: seed   Source File: RabbitMQConfiguration.java    License: 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 5
Source Project: blog_demos   Source File: RabbitTemplateConfig.java    License: 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 6
@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 7
Source Project: demo_springboot_rabbitmq   Source File: AmqpConfig.java    License: 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 8
Source Project: hawkbit   Source File: AmqpTestConfiguration.java    License: 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 Project: hawkbit   Source File: AmqpConfiguration.java    License: 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 10
@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 11
@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 12
Source Project: summerframework   Source File: PublishTraceLog.java    License: 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 13
Source Project: hawkbit   Source File: AmqpConfiguration.java    License: 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 14
Source Project: blog_demos   Source File: RabbitConfig.java    License: 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 15
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 16
/**
 * @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 17
Source Project: brave   Source File: ITSpringRabbit.java    License: 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 18
Source Project: blog_demos   Source File: RabbitTemplateConfig.java    License: 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 19
Source Project: rome   Source File: RabbitMQConfig.java    License: 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 20
Source Project: rabbitmq-mock   Source File: SpringIntegrationTest.java    License: 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 21
Source Project: brave   Source File: SpringRabbitTracingTest.java    License: 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 22
@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 23
Source Project: brave   Source File: SpringRabbitTracingTest.java    License: 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 24
Source Project: cukes   Source File: RabbitMQConfiguration.java    License: 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 25
Source Project: brave   Source File: ITSpringRabbit.java    License: 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
@Test
public void contextShouldLoad() {
    assertThat(environment.getPropertySources())
        .extracting(PropertySource::getName)
        .containsExactly(
            "configurationProperties",
            "Inlined Test Properties",
            "systemProperties",
            "systemEnvironment",
            "random",
            "applicationConfig: [classpath:/application.properties]",
            "flowableDefaultConfig: [classpath:/flowable-default.properties]",
            "flowable-liquibase-override",
            "Management Server"
        );

    assertThat(applicationContext.getBeanProvider(JmsTemplate.class).getIfAvailable())
        .as("JmsTemplate Bean")
        .isNotNull();

    assertThat(applicationContext.getBeanProvider(ConnectionFactory.class).getIfAvailable())
        .as("Jms ConnectionFactory Bean")
        .isNotNull();

    assertThat(applicationContext.getBeanProvider(org.springframework.amqp.rabbit.connection.ConnectionFactory.class).getIfAvailable())
        .as("Rabbit ConnectionFactory Bean")
        .isNotNull();

    assertThat(applicationContext.getBeanProvider(RabbitTemplate.class).getIfAvailable())
        .as("RabbitTemplate Bean")
        .isNotNull();

    assertThat(applicationContext.getBeanProvider(ConsumerFactory.class).getIfAvailable())
        .as("Kafka ConsumerFactory Bean")
        .isNotNull();

    assertThat(applicationContext.getBeanProvider(KafkaTemplate.class).getIfAvailable())
        .as("KafkaTemplate Bean")
        .isNotNull();

    assertThat(applicationContext.getBeansOfType(ChannelModelProcessor.class))
        .containsOnlyKeys(
            "jmsChannelDefinitionProcessor",
            "kafkaChannelDefinitionProcessor",
            "rabbitChannelDefinitionProcessor"
        );
}
 
Example 27
Source Project: pinpoint   Source File: ReceiverConfig_Pre_1_6_0.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public TestReceiver testReceiver(RabbitTemplate rabbitTemplate) {
    return new TestReceiver_Pre_1_6_0(rabbitTemplate);
}
 
Example 28
Source Project: konker-platform   Source File: EventSchemaServiceTest.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    return Mockito.mock(RabbitTemplate.class);
}
 
Example 29
@Bean
public RabbitTemplate rabbitTemplate() {
    return mock(RabbitTemplate.class);
}
 
Example 30
Source Project: OpenSZZ-Cloud-Native   Source File: Runner.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Runner (RabbitTemplate rabbitTemplate) {
    this.rabbitTemplate = rabbitTemplate;
}