1
\$\begingroup\$

The publisher class:

@Service
public class RabbitMQPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQPublisher.class);
private final RabbitTemplate rabbitTemplate;
@Value("${message.broker.rabbitmq.consumer-update-queue}")
private String topic;
public RabbitMQPublisher(final RabbitTemplate rabbitTemplate) {
 this.rabbitTemplate = rabbitTemplate;
}
/**
 * Publishes a message to RabbitMQ.
 *
 * @param message the payload to send
 */
public void publishEvent(final SomeDto message) {
 try {
 rabbitTemplate.convertAndSend(topic, message);
 LOGGER.debug("Published message to topic {}: {}", topic, message);
 } catch (Exception ex) {
 LOGGER.error("Failed to publish message to topic {}: {}", topic, ex.getMessage());
 }
}
}

The Configuration class :

@Configuration
public class RabbitMQPublisherConfig {
@Value("${spring.rabbitmq.host}")
private String rabbitHost;
@Value("${spring.rabbitmq.port}")
private int rabbitPort;
@Value("${spring.rabbitmq.username}")
private String rabbitUsername;
@Value("${spring.rabbitmq.password}")
private String rabbitPassword;
@Bean
public ConnectionFactory connectionFactory() {
 CachingConnectionFactory factory = new CachingConnectionFactory(rabbitHost);
 factory.setPort(rabbitPort);
 factory.setUsername(rabbitUsername);
 factory.setPassword(rabbitPassword);
 return factory;
 }
@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter(final ObjectMapper objectMapper) {
 return new Jackson2JsonMessageConverter(objectMapper);
}
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory,
 final Jackson2JsonMessageConverter messageConverter) {
 RabbitTemplate template = new RabbitTemplate(connectionFactory);
 template.setMessageConverter(messageConverter);
 return template;
}
}
  • Is this the correct and efficient way to publish JSON messages using Spring Boot and RabbitMQ?
  • Are there any best practices I’m missing?
  • Should I register the Jackson2JsonMessageConverter differently if I’m only a publisher?
  • Any feedback on exception handling or overall design?
toolic
15.1k5 gold badges29 silver badges211 bronze badges
asked Jul 12 at 10:58
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.