Amazon SQS Java 메시징 라이브러리 시작 - Amazon Simple Queue Service

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Amazon SQS Java 메시징 라이브러리 시작

Amazon SQS에서 Java 메시지 서비스(JMS) 사용을 시작하려면 이 섹션의 코드 예제를 사용합니다. 다음 섹션에는 JMS 연결 및 세션 생성 방법과 메시지 전송 및 수신 방법이 나와 있습니다.

Amazon SQS Java 메시징 라이브러리에 포함된 래핑된 Amazon SQS 클라이언트 객체는 Amazon SQS 대기열이 존재하는지 확인합니다. 대기열이 존재하지 않는 경우, 클라이언트가 이 대기열을 생성합니다.

JMS 연결 생성

  1. 연결 팩토리를 생성하고 이 팩토리에 대한 createConnection 메서드를 호출합니다.

    // Create a new connection factory with all defaults (credentials and region) set automatically SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.defaultClient() ); // Create the connection. SQSConnection connection = connectionFactory.createConnection();

    SQSConnection 클래스는 javax.jms.Connection을 확장합니다. JMS 표준 연결 메서드와 더불어 SQSConnectiongetAmazonSQSClientgetWrappedAmazonSQSClient와 같은 추가 메서드를 제공합니다. 이 두 메서드를 통해 새로운 대기열 생성과 같이 JMS 사양에 포함되지 않은 관리 작업을 수행할 수 있습니다. 그렇지만, getWrappedAmazonSQSClient 메서드는 최신 연결을 통해 사용되는 래핑된 버전의 Amazon SQS 클라이언트도 제공합니다. 래퍼는 클라이언트에서 JMSException으로 모든 예외를 변환하므로, JMSException 발생이 예상되는 기존 코드에서 보다 쉽게 사용할 수 있습니다.

  2. getAmazonSQSClientgetWrappedAmazonSQSClient에서 반환되는 클라이언트 객체를 사용하여 JMS 사양에 포함되지 않은 관리 작업(예: Amazon SQS 대기열 생성 가능)을 수행할 수 있습니다.

    JMS 예외가 예상되는 기존 코드가 있는 경우, getWrappedAmazonSQSClient를 사용해야 합니다.

    • getWrappedAmazonSQSClient를 사용한 경우, 반환된 클라이언트 객체는 모든 예외를 JMS 예외로 변환합니다.

    • getAmazonSQSClient를 사용하는 경우, 예외는 모두 Amazon SQS 예외입니다.

Amazon SQS 대기열 생성

래핑된 클라이언트 객체는 Amazon SQS 대기열이 있는지를 확인합니다.

대기열이 존재하지 않는 경우, 클라이언트가 이 대기열을 생성합니다. 대기열이 존재하지 않는 경우, 이 함수는 어느 항목도 반환하지 않습니다. 자세한 내용은 TextMessageSender.java 예제에서 "필요한 경우 대기열 생성"을 참조하십시오.

표준 대기열을 생성하려면

// Get the wrapped client AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); // Create an SQS queue named MyQueue, if it doesn't already exist if (!client.queueExists("MyQueue")) { client.createQueue("MyQueue"); }

FIFO 대기열을 생성하려면

// Get the wrapped client AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); // Create an Amazon SQS FIFO queue named MyQueue.fifo, if it doesn't already exist if (!client.queueExists("MyQueue.fifo")) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put("FifoQueue", "true"); attributes.put("ContentBasedDeduplication", "true"); client.createQueue(new CreateQueueRequest().withQueueName("MyQueue.fifo").withAttributes(attributes)); }
참고

FIFO 대기열의 이름은 .fifo 접미사로 끝나야 합니다.

ContentBasedDeduplication 속성에 대한 자세한 내용은 정확히 1회 처리를 참조하십시오.

메시지 동기식 전송

  1. 연결 및 기본 Amazon SQS 대기열이 준비가 되면, AUTO_ACKNOWLEDGE 모드로 트랜잭션 처리되지 않는 JMS 세션을 생성합니다.

    // Create the nontransacted session with AUTO_ACKNOWLEDGE mode Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  2. 대기열에 문자 메시지를 전송하려면, JMS 대기열 자격 증명과 메시지 생성자를 생성합니다.

    // Create a queue identity and specify the queue name to the session Queue queue = session.createQueue("MyQueue"); // Create a producer for the 'MyQueue' MessageProducer producer = session.createProducer(queue);
  3. 문자 메시지를 작성하고 대기열로 전송합니다.

    • 메시지를 표준 대기열로 전송하는 경우 추가 파라미터를 설정할 필요가 없습니다.

      // Create the text message TextMessage message = session.createTextMessage("Hello World!"); // Send the message producer.send(message); System.out.println("JMS Message " + message.getJMSMessageID());
    • 메시지를 FIFO 대기열로 전송하는 경우 메시지 그룹 ID를 설정해야 합니다. 메시지 중복 제거 ID를 설정할 수도 있습니다. 자세한 내용은 주요 용어 섹션을 참조하세요.

      // Create the text message TextMessage message = session.createTextMessage("Hello World!"); // Set the message group ID message.setStringProperty("JMSXGroupID", "Default"); // You can also set a custom message deduplication ID // message.setStringProperty("JMS_SQS_DeduplicationId", "hello"); // Here, it's not needed because content-based deduplication is enabled for the queue // Send the message producer.send(message); System.out.println("JMS Message " + message.getJMSMessageID()); System.out.println("JMS Message Sequence Number " + message.getStringProperty("JMS_SQS_SequenceNumber"));

메시지 동기식 수신

  1. 메시지를 수신하려면 동일한 대기열에 대한 소비자를 생성하고 start 메서드를 호출합니다.

    언제든지 연결에서 start 메서드를 호출할 수 있습니다. 그렇지만, 소비자는 사용자가 메시지를 호출할 때까지 메시지 수신을 시작하지 않습니다.

    // Create a consumer for the 'MyQueue' MessageConsumer consumer = session.createConsumer(queue); // Start receiving incoming messages connection.start();
  2. 제한 시간을 1초로 설정한 소비자에서 receive 메서드를 호출한 다음 수신된 메시지의 내용을 인쇄합니다.

    • 표준 대기열에서 메시지를 수신한 후 해당 메시지의 내용에 액세스할 수 있습니다.

      // Receive a message from 'MyQueue' and wait up to 1 second Message receivedMessage = consumer.receive(1000); // Cast the received message as TextMessage and display the text if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); }
    • FIFO 대기열에서 메시지를 수신한 후 메시지 그룹 ID, 메시지 중복 제거 ID 및 시퀀스 번호와 같은 메시지 내용 및 기타 FIFO 관련 메시지 속성에 액세스할 수 있습니다. 자세한 내용은 주요 용어 섹션을 참조하세요.

      // Receive a message from 'MyQueue' and wait up to 1 second Message receivedMessage = consumer.receive(1000); // Cast the received message as TextMessage and display the text if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); System.out.println("Group id: " + receivedMessage.getStringProperty("JMSXGroupID")); System.out.println("Message deduplication id: " + receivedMessage.getStringProperty("JMS_SQS_DeduplicationId")); System.out.println("Message sequence number: " + receivedMessage.getStringProperty("JMS_SQS_SequenceNumber")); }
  3. 연결과 세션을 종료합니다.

    // Close the connection (and the session). connection.close();

출력 결과는 다음과 비슷합니다:

JMS Message ID:8example-588b-44e5-bbcf-d816example2 Received: Hello World!
참고

Spring Framework를 사용하여 이 객체를 초기화할 수 있습니다.

추가 정보는 SpringExampleConfiguration.xml, SpringExample.javaExampleConfiguration.java 단원의 ExampleCommon.javaAmazon SQS 표준 대기열에 JMS를 사용하는 Java 작업 예제에 있는 기타 헬퍼 클래스를 참조하십시오.

객체 전송 및 수신 예제 전체를 보려면, TextMessageSender.javaSyncMessageReceiver. 자바를 참조하십시오.

메시지 비동기식 수신

Amazon SQS Java 메시징 라이브러리 시작의 예제에서 메시지는 MyQueue로 전송되고 동기식으로 수신됩니다.

다음 예제는 리스너를 통해 비동기식으로 메시지를 수신하는 방법을 나타냅니다.

  1. MessageListener 인터페이스를 구현합니다.

    class MyListener 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(); } } }

    메시지를 수신하면 MessageListener 인터페이스의 onMessage 메서드가 호출됩니다. 이 리스너 구현에서 메시지에 저장된 텍스트가 인쇄됩니다.

  2. 소비자에서 receive 메서드를 명시적으로 호출하지 않고, 소비자의 메시지 리스너를 MyListener 구현의 인스턴스로 설정합니다. 기본 스레드는 1초간 대기합니다.

    // Create a consumer for the 'MyQueue'. MessageConsumer consumer = session.createConsumer(queue); // Instantiate and set the message listener for the consumer. consumer.setMessageListener(new MyListener()); // Start receiving incoming messages. connection.start(); // Wait for 1 second. The listener onMessage() method is invoked when a message is received. Thread.sleep(1000);

나머지 단계는 Amazon SQS Java 메시징 라이브러리 시작 예제의 단계와 동일합니다. 비동기식 소비자의 예제 전체는 AsyncMessageReceiver.javaAmazon SQS 표준 대기열에 JMS를 사용하는 Java 작업 예제를 참조하십시오.

이 예제의 출력은 다음과 비슷합니다.

JMS Message ID:8example-588b-44e5-bbcf-d816example2 Received: Hello World!

클라이언트 승인 모드 사용

Amazon SQS Java 메시징 라이브러리 시작의 예제는 모든 수신 메시지가 자동으로 승인되고 나서 기본 Amazon SQS 대기열에서 삭제되는 AUTO_ACKNOWLEDGE 모드를 사용합니다.

  1. 메시지를 처리한 후 명시적으로 승인하려면, CLIENT_ACKNOWLEDGE 모드로 세션을 생성해야 합니다.

    // Create the non-transacted session with CLIENT_ACKNOWLEDGE mode. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
  2. 메시지를 수신하면 메시지를 표시한 후 명시적으로 승인합니다.

    // Cast the received message as TextMessage and print the text to screen. Also acknowledge the message. if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); receivedMessage.acknowledge(); System.out.println("Acknowledged: " + message.getJMSMessageID()); }
    참고

    이 모드에서 메시지를 승인하면, 이 메시지를 이전에 받은 모든 메시지도 명시적으로 승인됩니다. 예를 들어, 메시지 10개를 수신하고 10번째(메시지 수신 순서) 메시지만을 승인하면, 이전의 9개 메시지 전체도 승인됩니다.

나머지 단계는 Amazon SQS Java 메시징 라이브러리 시작 예제의 단계와 동일합니다. 클라이언트 승인 모드를 사용하는 비동기식 소비자의 예제 전체는 SyncMessageReceiverClientAcknowledge.javaAmazon SQS 표준 대기열에 JMS를 사용하는 Java 작업 예제를 참조하십시오.

이 예제의 출력은 다음과 비슷합니다.

JMS Message ID:4example-aa0e-403f-b6df-5e02example5 Received: Hello World! Acknowledged: ID:4example-aa0e-403f-b6df-5e02example5

정렬되어 있지 않은 승인 모드 사용

CLIENT_ACKNOWLEDGE 모드를 사용하면, 명시적으로 승인한 메시지 이전에 받은 모든 메시지가 자동으로 승인됩니다. 자세한 내용은 클라이언트 승인 모드 사용 섹션을 참조하세요.

Amazon SQS Java 메시징 라이브러리는 또 다른 승인 모드를 제공합니다. UNORDERED_ACKNOWLEDGE 모드를 사용하면, 수신한 모든 메시지가 수신 순서에 상관 없이 개별적 및 명시적으로 승인됩니다. 이렇게 하려면 UNORDERED_ACKNOWLEDGE 모드를 사용하여 세션을 생성합니다.

// Create the non-transacted session with UNORDERED_ACKNOWLEDGE mode. Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE);

나머지 단계는 클라이언트 승인 모드 사용 예제의 단계와 동일합니다. UNORDERED_ACKNOWLEDGE 모드에서 동기식 소비자의 예제 전체는 SyncMessageReceiverUnorderedAcknowledge.java를 참조하십시오.

이 예제의 출력은 다음과 비슷합니다.

JMS Message ID:dexample-73ad-4adb-bc6c-4357example7 Received: Hello World! Acknowledged: ID:dexample-73ad-4adb-bc6c-4357example7