Skip to main content
Code Review

Return to Question

edited title
Link
toolic
  • 15.1k
  • 5
  • 29
  • 211

Spring Boot RabbitMQ Publisher Configuration – Is This Setup Correct for Sending JSON Messages?

Source Link

Spring Boot RabbitMQ Publisher Configuration – Is This Setup Correct for Sending JSON Messages?

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?
lang-java

AltStyle によって変換されたページ (->オリジナル) /