-
-
Save tacsio/5ffbf15f83d25adebe517c62099a16ad to your computer and use it in GitHub Desktop.
Sample RabbitmqConfig if you don't have __TypeID__ but have other header (for example : type)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.amqp.core.Message; | |
import org.springframework.amqp.core.MessagePostProcessor; | |
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; | |
import org.springframework.amqp.rabbit.connection.ConnectionFactory; | |
import org.springframework.amqp.rabbit.core.RabbitTemplate; | |
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; | |
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import com.course.finance.message.invoice.InvoiceCreatedMessage; | |
import com.course.finance.message.invoice.InvoicePaidMessage; | |
@Configuration | |
public class RabbitmqConfig { | |
@Bean(name = "rabbitListenerContainerFactory") | |
public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory( | |
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { | |
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); | |
configurer.configure(factory, connectionFactory); | |
factory.setAfterReceivePostProcessors(new MessagePostProcessor() { | |
@Override | |
public Message postProcessMessage(Message message) throws AmqpException { | |
var type = message.getMessageProperties().getHeaders().get("type").toString(); | |
String typeId = null; | |
if (StringUtils.equalsIgnoreCase(type, "invoice.paid")) { | |
typeId = InvoicePaidMessage.class.getName(); | |
} else if (StringUtils.equalsIgnoreCase(type, "invoice.created")) { | |
typeId = InvoiceCreatedMessage.class.getName(); | |
} | |
Optional.ofNullable(typeId).ifPresent(t -> message.getMessageProperties().setHeader("__TypeId__", t)); | |
return message; | |
} | |
}); | |
return factory; | |
} | |
@Bean | |
Jackson2JsonMessageConverter jsonMessageConverter() { | |
return new Jackson2JsonMessageConverter(); | |
} | |
@Bean | |
RabbitTemplate rabbitTemplate(Jackson2JsonMessageConverter converter, ConnectionFactory connectionFactory) { | |
RabbitTemplate template = new RabbitTemplate(connectionFactory); | |
template.setMessageConverter(new Jackson2JsonMessageConverter()); | |
return template; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment