18 Aralık 2022 Pazar

AWS SQS API @SqsListener Anotasyonu

Maven
Şu satırı dahil ederiz
<dependency>
<groupId>io.awspring.cloud</groupId> <artifactId>spring-cloud-aws-starter-sqs</artifactId> <version>3.0.0-M3</version> </dependency>
Örnek - Spring
application.properties şöyle olsun
spring:
 ...
  cloud:
    aws:
      sqs:
        endpoint: http://localhost:4566
        region: us-east-1
Şöyle yaparız
import io.awspring.cloud.sqs.annotation.SqsListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class PortfolioConsumer {
  private final ObjectMapper objectMapper;
  private final PortfolioRepository portfolioRepository;
  public PortfolioConsumer(final ObjectMapper objectMapper,
                           final PortfolioRepository portfolioRepository) {
    this.objectMapper = objectMapper;
    this.portfolioRepository = portfolioRepository;
  }
  @SqsListener(value = "${consumer.portfolio.queue-name}")
  public void consume(final Message<String> message){
    try {
      var body = objectMapper.readTree(message.getPayload()).get("Message").textValue();
      var portfolioConsumerDTO = objectMapper.readValue(body, PortfolioConsumerDTO.class);

      portfolioRepository.save(new Portfolio(portfolioConsumerDTO.id(), portfolioConsumerDTO.name()));

      log.info(String.format("receive message portfolio: id  %s", portfolioConsumerDTO.id()));
     } catch (Throwable e){
       var errorMsg = "got error at consumer portfolioDTO";
       throw new ConsumerException(errorMsg, e);
    }
  }
  @MessageExceptionHandler(value = ConsumerException.class)
  void handlerException(final ConsumerException e){
    log.error("handlerException", e);
  }
}


Hiç yorum yok:

Yorum Gönder