AWS

Simple Queue Service_Spring Boot 2.x

Raconer 2023. 4. 16. 23:48
728x90

적용

Spring Boot에 적용

Dependency

    implementation 'com.amazonaws:amazon-sqs-java-messaging-lib:2.0.2'

Config 설정

    @Configuration
    public class SQSConfig {

        // application.properties or yml 에 작성하고 @Value를 사용하여되된다.
        private String accessKey = "";
        private String secretKey = "";

        @Bean
        public SQSConnection amazonSQSAws() throws JMSException {

            ProviderConfiguration configuration = new ProviderConfiguration();

            SqsClient sqsClient = SqsClient.builder()
                    .region(Region.***) // 사용하는 지역
                    .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(this.accessKey, this.secretKey)))
                    .build();

            SQSConnectionFactory connectionFactory = new SQSConnectionFactory(configuration, sqsClient);

            return connectionFactory.createConnection();
        }
    }

Service 생성

  • 공통으로 SQSConnection sqsConnection; DI 해야한다.

Send

    String QUEUE = "본인이 생성한 SQS 대기열";

     public void sendMsg(String msg) {
        AmazonSQSMessagingClientWrapper client = this.sqsConnection.getWrappedAmazonSQSClient();

        try {
            if (client.queueExists(QUEUE)) {
                Session session = this.sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                Queue queue = session.createQueue(QUEUE);

                MessageProducer producer = session.createProducer(queue);

                // Create the text message
                TextMessage message = session.createTextMessage(msg);
                // Set the message group ID
                message.setStringProperty("JMSXGroupID", "Default");
                // Send the message

                producer.send(message);
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

Receive


    String QUEUE = "본인이 생성한 SQS 대기열";

       public void receiveMsg(){

        try {
            Session session = this.sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Queue queue = session.createQueue(QUEUE);
            // Create a consumer for the 'MyQueue'
            MessageConsumer consumer = session.createConsumer(queue);

            // Start receiving incoming messages
            this.sqsConnection.start();

            Message receivedMessage = consumer.receive();

            // Cast the received message as TextMessage and display the text
            if (receivedMessage != null) {
                System.out.println("Received: " + ((TextMessage) receivedMessage).getText());
            }else{
                System.out.println("NOT RECEIVE MESSAGE");
            }

            this.sqsConnection.close();

        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

Async Receive

Async Receive Code

    String QUEUE = "본인이 생성한 SQS 대기열";
       public void asyncReceiveMsg(){
        System.out.println("Async Receive Start");
        try {
            Session session = this.sqsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(QUEUE);
            // Create a consumer for the 'MyQueue'.
            MessageConsumer consumer = session.createConsumer(queue);

            // Instantiate and set the message listener for the consumer.
            consumer.setMessageListener(new SQSListener());

            // Start receiving incoming messages.
            this.sqsConnection.start();

            // 10초
            Thread.sleep(10000);

        } catch (JMSException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

Async Receive Listener

 */
  public class SQSListener implements MessageListener {

      @Override
      public void onMessage(Message message) {
          try {
              // Cast the received message as TextMessage and print the text to screen.
              System.out.println("Received: " + ((TextMessage) message).getText());
          } catch (JMSException e) {
              e.printStackTrace();
          }
      }
  }

참고

728x90

'AWS' 카테고리의 다른 글

[SES] AWS Simple Email Service & Spring Boot(Kotlin)  (0) 2024.10.09
로드밸런스 알고리즘 종류  (0) 2023.07.05
Simple Queue Service_이론  (0) 2023.04.16
Spring Boot, Ubuntu, Nginx 배포 방법  (0) 2023.04.16