|
| 1 | +package com.flowci.common.business; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.flowci.common.model.RabbitEvent; |
| 6 | +import lombok.extern.slf4j.Slf4j; |
| 7 | +import org.springframework.amqp.core.Message; |
| 8 | +import org.springframework.amqp.rabbit.core.RabbitTemplate; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.stereotype.Component; |
| 11 | + |
| 12 | +import static com.flowci.common.config.AmqpConfig.EXCHANGE_NAME; |
| 13 | + |
| 14 | +@Slf4j |
| 15 | +@Component |
| 16 | +public class PublishRabbitEventImpl implements PublishRabbitEvent { |
| 17 | + |
| 18 | + private final static Long WAIT_TIMEOUT = 5000L; // 5 seconds |
| 19 | + |
| 20 | + private final RabbitTemplate rabbitTemplate; |
| 21 | + private final ObjectMapper objectMapper; |
| 22 | + |
| 23 | + public PublishRabbitEventImpl(@Autowired(required = false) RabbitTemplate rabbitTemplate, |
| 24 | + ObjectMapper objectMapper) { |
| 25 | + this.rabbitTemplate = rabbitTemplate; |
| 26 | + this.objectMapper = objectMapper; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public void invoke(RabbitEvent event) { |
| 31 | + if (rabbitTemplate == null) { |
| 32 | + log.debug("rabbitmq is not configured"); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + try { |
| 37 | + var eventJson = objectMapper.writeValueAsString(event); |
| 38 | + rabbitTemplate.send(EXCHANGE_NAME, event.getRoutingKey(), new Message(eventJson.getBytes())); |
| 39 | + |
| 40 | + if (rabbitTemplate.waitForConfirms(WAIT_TIMEOUT)) { |
| 41 | + log.info("Event {} published successfully", eventJson); |
| 42 | + } |
| 43 | + } catch (JsonProcessingException e) { |
| 44 | + log.error("unable parse event to json", e); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments