-
Notifications
You must be signed in to change notification settings - Fork 5
RabbitMQ Publisher
shoecillo edited this page Oct 30, 2017
·
2 revisions
This module have the functionality of publish messages on rabbitMQ.
Also have REST controllers for publish messages with HTTP calls.
This is the module structure:
│ pom.xml
├───src
├───main
├───java
│ └───com
│ └───sh
│ ├───app
│ │ AppRabbitPublisher.java
│ │
│ ├───ctrl
│ │ RabbitController.java
│ │
│ └───producers
│ MsgProducer.java
│
└───resources
application.properties
Look the configuration.
With this we declare a queue,a topic exchange and a binder of both:
@Bean(name ="queueCustomer")
Queue queueCustomer() {
return new Queue(qCustomer, true);
}
@Bean(name="exchangeCustomer")
TopicExchange exchangeCustomer() {
return new TopicExchange(topicName);
}
@Bean(name="bindingCustomer")
Binding bindingCustomer(Queue queueCustomer, TopicExchange exchangeCustomer) {
return BindingBuilder.bind(queueCustomer).to(exchangeCustomer).with(qCustomer);
}Next step is declare a connectionFactory with the rabbitMQ host(brokerUrl) and configure a json message converter:
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(brokerUrl);
connectionFactory.setUsername(user);
connectionFactory.setPassword(pwd);
return connectionFactory;
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}Last step is configure the rabbitTemplate:
@Bean(name="rabbitTemplateCustomer")
public RabbitTemplate rabbitTemplateCustomer() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setRoutingKey(qCustomer);
template.setMessageConverter(jsonMessageConverter());
return template;
}This configuration is in AppRabbitPublisher.java
Class MsgProducer is the component that publish in rabbit:
@Autowired
@Qualifier("rabbitTemplateCustomer")
private RabbitTemplate rabbitCustomer;
private static final Logger LOGGER = LoggerFactory.getLogger(MsgProducer.class);
/**
* Convert and send CustomerMsg object to Rabbit
* @param msg - CustomerMsg
* @see CustomerMsg
*/
public void sendCustomerMsg(CustomerMsg msg)
{
try {
LOGGER.debug("<<<<<< SENDING MESSAGE");
rabbitCustomer.convertAndSend(msg);
LOGGER.debug(MessageFormat.format("MESSAGE SENT TO {0} >>>>>>", rabbitCustomer.getRoutingKey()));
} catch (AmqpException e) {
LOGGER.error("Error sending Customer: ",e);
}
}The operation [rabbitCustomer.convertAndSend(msg)] convert msg in JSON and send to rabbitMQ configured queue.
The other class is a REST controller with little API for publish messages.