

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Menggunakan JMS dengan Amazon SQS
<a name="sqs-java-message-service-jms-client"></a>

Amazon SQS Java Messaging Library adalah antarmuka Java Message Service (JMS) untuk Amazon SQS yang memungkinkan Anda memanfaatkan Amazon SQS dalam aplikasi yang sudah menggunakan JMS. Antarmuka memungkinkan Anda menggunakan Amazon SQS sebagai penyedia JMS dengan perubahan kode minimal. Bersama dengan AWS SDK untuk Java, Amazon SQS Java Messaging Library memungkinkan Anda membuat koneksi dan sesi JMS, serta produsen dan konsumen yang mengirim dan menerima pesan ke dan dari antrian Amazon SQS.

Pustaka mendukung pengiriman dan penerimaan pesan ke antrian ( point-to-pointmodel JMS) sesuai dengan spesifikasi [JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html). Pustaka mendukung pengiriman pesan teks, byte, atau objek secara sinkron ke antrian Amazon SQS. Pustaka juga mendukung penerimaan objek secara sinkron atau asinkron.

[Untuk informasi tentang fitur Amazon SQS Java Messaging Library yang mendukung spesifikasi JMS 1.1, lihat [Amazon SQS mendukung implementasi JMS 1.1](supported-implementations.md) dan Amazon SQS. FAQs](https://aws.amazon.com/sqs/faqs/)

# Prasyarat untuk bekerja dengan JMS dan Amazon SQS
<a name="prerequisites"></a>

Sebelum Anda mulai, Anda harus memiliki prasyarat berikut:
+ **SDK for Java**

  Ada dua cara untuk menyertakan SDK for Java dalam proyek Anda:
  + Unduh dan instal SDK for Java.
  + Gunakan Maven untuk mendapatkan Amazon SQS Java Messaging Library.
**catatan**  
SDK for Java disertakan sebagai dependensi.  
[SDK for](https://aws.amazon.com/sdkforjava/) Java dan Amazon SQS Extended Client Library untuk Java memerlukan J2SE Development Kit 8.0 atau yang lebih baru.

    Untuk informasi tentang mengunduh SDK for Java, [lihat SDK](https://aws.amazon.com/sdkforjava/) for Java.
+ **Perpustakaan Pesan Amazon SQS Java** 

  Jika Anda tidak menggunakan Maven, Anda harus menambahkan `amazon-sqs-java-messaging-lib.jar` paket ke jalur kelas Java. Untuk informasi tentang mengunduh pustaka, lihat [Amazon SQS Java Messaging](https://github.com/awslabs/amazon-sqs-java-messaging-lib) Library.
**catatan**  
[Amazon SQS Java Messaging Library mencakup dukungan untuk [Maven](http://maven.apache.org/) dan Spring Framework.](http://projects.spring.io/spring-framework/)  
Untuk contoh kode yang menggunakan Maven, Spring Framework, dan Amazon SQS Java Messaging Library, lihat. [Contoh Java yang berfungsi untuk menggunakan JMS dengan antrian standar Amazon SQS](sqs-jms-code-examples.md)  

  ```
  <dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>amazon-sqs-java-messaging-lib</artifactId>
    <version>1.0.4</version>
    <type>jar</type>
  </dependency>
  ```
+ **Antrian Amazon SQS**

  Buat antrian menggunakan Konsol Manajemen AWS for Amazon SQS, API, atau klien Amazon SQS `CreateQueue` yang dibungkus yang disertakan dalam Amazon SQS Java Messaging Library.
  + Untuk informasi tentang membuat antrian dengan Amazon SQS menggunakan API atau `CreateQueue` API, [lihat Membuat](creating-sqs-standard-queues.md#step-create-standard-queue) Antrian. Konsol Manajemen AWS 
  + Untuk informasi tentang menggunakan Amazon SQS Java Messaging Library, lihat. [Menggunakan Amazon SQS Java Messaging Library](getting-started.md)

# Menggunakan Amazon SQS Java Messaging Library
<a name="getting-started"></a>

Untuk mulai menggunakan Java Message Service (JMS) dengan Amazon SQS, gunakan contoh kode di bagian ini. Bagian berikut menunjukkan cara membuat koneksi JMS dan sesi, dan cara mengirim dan menerima pesan.

Objek klien Amazon SQS yang dibungkus yang disertakan dalam Perpustakaan Pesan Java Amazon SQS memeriksa apakah antrian Amazon SQS ada. Jika antrian tidak ada, klien membuatnya.

## Membuat koneksi JMS
<a name="creating-connection"></a>

Sebelum Anda mulai, lihat prasyarat di. [Prasyarat untuk bekerja dengan JMS dan Amazon SQS](prerequisites.md)

1. Buat pabrik koneksi dan panggil `createConnection` metode melawan pabrik.

   ```
   // 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`Kelas meluas. `javax.jms.Connection` Bersama dengan metode koneksi standar JMS, `SQSConnection` menawarkan metode tambahan, seperti `getAmazonSQSClient` dan`getWrappedAmazonSQSClient`. Kedua metode memungkinkan Anda melakukan operasi administratif yang tidak termasuk dalam spesifikasi JMS, seperti membuat antrian baru. Namun, `getWrappedAmazonSQSClient` metode ini juga menyediakan versi terbungkus dari klien Amazon SQS yang digunakan oleh koneksi saat ini. Pembungkus mengubah setiap pengecualian dari klien menjadi`JMSException`, memungkinkannya untuk lebih mudah digunakan oleh kode yang ada yang mengharapkan `JMSException` kejadian.

1. Anda dapat menggunakan objek klien yang dikembalikan dari `getAmazonSQSClient` dan `getWrappedAmazonSQSClient` untuk melakukan operasi administratif yang tidak termasuk dalam spesifikasi JMS (misalnya, Anda dapat membuat antrean Amazon SQS).

    Jika Anda memiliki kode yang mengharapkan pengecualian JMS, maka Anda harus menggunakan: `getWrappedAmazonSQSClient`
   + Jika Anda menggunakan`getWrappedAmazonSQSClient`, objek klien yang dikembalikan mengubah semua pengecualian menjadi pengecualian JMS.
   + Jika Anda menggunakan`getAmazonSQSClient`, pengecualian adalah semua pengecualian Amazon SQS.

## Membuat antrian Amazon SQS
<a name="creating-queue"></a>

Objek klien yang dibungkus memeriksa apakah antrian Amazon SQS ada.

Jika antrian tidak ada, klien membuatnya. Jika antrian memang ada, fungsi tidak mengembalikan apa pun. Untuk informasi selengkapnya, lihat bagian “Buat antrian jika diperlukan” pada [TextMessageSender.jawa](sqs-jms-code-examples.md#example-sender) contoh.

### Untuk membuat antrian standar
<a name="creating-queue-standard"></a>

```
// 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");
}
```

### Untuk membuat antrian FIFO
<a name="creating-queue-FIFO"></a>

```
// 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));
}
```

**catatan**  
Nama antrian FIFO harus diakhiri dengan akhiran. `.fifo`  
Untuk informasi selengkapnya tentang `ContentBasedDeduplication` atribut, lihat[Tepat sekali diproses di Amazon SQS](FIFO-queues-exactly-once-processing.md).

## Mengirim pesan secara sinkron
<a name="send-messages-synchronously"></a>

1. Saat koneksi dan antrean Amazon SQS yang mendasarinya sudah siap, buat sesi JMS yang tidak ditransaksikan dengan mode. `AUTO_ACKNOWLEDGE`

   ```
   // Create the nontransacted session with AUTO_ACKNOWLEDGE mode
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   ```

1. Untuk mengirim pesan teks ke antrian, buat identitas antrian JMS dan produser pesan.

   ```
   // 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);
   ```

1. Buat pesan teks dan kirimkan ke antrian.
   + Untuk mengirim pesan ke antrian standar, Anda tidak perlu mengatur parameter tambahan apa pun.

     ```
     // Create the text message
     TextMessage message = session.createTextMessage("Hello World!");
      
     // Send the message
     producer.send(message);
     System.out.println("JMS Message " + message.getJMSMessageID());
     ```
   + Untuk mengirim pesan ke antrian FIFO, Anda harus mengatur ID grup pesan. Anda juga dapat mengatur ID deduplikasi pesan. Untuk informasi selengkapnya, lihat [Istilah kunci antrian Amazon SQS FIFO](FIFO-key-terms.md).

     ```
     // 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"));
     ```

## Menerima pesan secara sinkron
<a name="receive-messages-synchronously"></a>

1. Untuk menerima pesan, buat konsumen untuk antrian yang sama dan panggil metode. `start`

   Anda dapat memanggil `start` metode pada koneksi kapan saja. Namun, konsumen tidak mulai menerima pesan sampai Anda memanggilnya.

   ```
   // Create a consumer for the 'MyQueue'
   MessageConsumer consumer = session.createConsumer(queue);
   // Start receiving incoming messages
   connection.start();
   ```

1. Panggil `receive` metode pada konsumen dengan batas waktu diatur ke 1 detik, dan kemudian cetak konten pesan yang diterima.
   + Setelah menerima pesan dari antrian standar, Anda dapat mengakses konten pesan.

     ```
     // 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());
     }
     ```
   + Setelah menerima pesan dari antrian FIFO, Anda dapat mengakses konten pesan dan atribut pesan khusus FIFO lainnya, seperti ID grup pesan, ID deduplikasi pesan, dan nomor urut. Untuk informasi selengkapnya, lihat [Istilah kunci antrian Amazon SQS FIFO](FIFO-key-terms.md).

     ```
     // 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"));
     }
     ```

1. Tutup koneksi dan sesi.

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

Output akan terlihat serupa dengan yang berikut ini:

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

**catatan**  
Anda dapat menggunakan Spring Framework untuk menginisialisasi objek-objek ini.  
Untuk informasi tambahan, lihat `SpringExampleConfiguration.xml``SpringExample.java`,, dan kelas pembantu lainnya di `ExampleConfiguration.java` dan `ExampleCommon.java` di [Contoh Java yang berfungsi untuk menggunakan JMS dengan antrian standar Amazon SQS](sqs-jms-code-examples.md) bagian.

Untuk contoh lengkap mengirim dan menerima objek, lihat [TextMessageSender.jawa](sqs-jms-code-examples.md#example-sender) dan[SyncMessageReceiver.jawa](sqs-jms-code-examples.md#example-synchronous-message-receiver).

## Menerima pesan secara asinkron
<a name="receive-messages-asynchronously"></a>

Dalam contoh di[Menggunakan Amazon SQS Java Messaging Library](#getting-started), pesan dikirim ke `MyQueue` dan diterima secara serempak.

Contoh berikut menunjukkan cara menerima pesan secara asinkron melalui pendengar.

1. Menerapkan `MessageListener` antarmuka.

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

   `onMessage`Metode `MessageListener` antarmuka dipanggil ketika Anda menerima pesan. Dalam implementasi listener ini, teks yang disimpan dalam pesan dicetak.

1. Alih-alih secara eksplisit memanggil `receive` metode pada konsumen, atur pendengar pesan konsumen ke instance implementasi. `MyListener` Utas utama menunggu satu detik.

   ```
   // 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);
   ```

Langkah-langkah lainnya identik dengan yang ada di [Menggunakan Amazon SQS Java Messaging Library](#getting-started) contoh. Untuk contoh lengkap konsumen asinkron, lihat di. `AsyncMessageReceiver.java` [Contoh Java yang berfungsi untuk menggunakan JMS dengan antrian standar Amazon SQS](sqs-jms-code-examples.md)

Output untuk contoh ini terlihat mirip dengan yang berikut:

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

## Menggunakan mode pengakuan klien
<a name="using-client-acknowledge-mode"></a>

Contoh dalam `AUTO_ACKNOWLEDGE` mode [Menggunakan Amazon SQS Java Messaging Library](#getting-started) penggunaan di mana setiap pesan yang diterima diakui secara otomatis (dan karenanya dihapus dari antrean Amazon SQS yang mendasarinya).

1. Untuk secara eksplisit mengakui pesan setelah diproses, Anda harus membuat sesi dengan mode. `CLIENT_ACKNOWLEDGE`

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

1. Ketika pesan diterima, tampilkan dan kemudian secara eksplisit mengakuinya.

   ```
   // 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());
   }
   ```
**catatan**  
Dalam mode ini, ketika pesan diakui, semua pesan yang diterima sebelum pesan ini secara implisit diakui juga. Misalnya, jika 10 pesan diterima, dan hanya pesan ke-10 yang diakui (dalam urutan pesan diterima), maka semua dari sembilan pesan sebelumnya juga diakui.

Langkah-langkah lainnya identik dengan yang ada di [Menggunakan Amazon SQS Java Messaging Library](#getting-started) contoh. Untuk contoh lengkap konsumen sinkron dengan mode pengakuan klien, lihat `SyncMessageReceiverClientAcknowledge.java` di. [Contoh Java yang berfungsi untuk menggunakan JMS dengan antrian standar Amazon SQS](sqs-jms-code-examples.md)

Output untuk contoh ini terlihat mirip dengan yang berikut:

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

## Menggunakan mode pengakuan tidak berurutan
<a name="using-unordered-acknowledge-mode"></a>

Saat menggunakan `CLIENT_ACKNOWLEDGE` mode, semua pesan yang diterima sebelum pesan yang diakui secara eksplisit diakui secara otomatis. Untuk informasi selengkapnya, lihat [Menggunakan mode pengakuan klien](#using-client-acknowledge-mode).

Amazon SQS Java Messaging Library menyediakan mode pengakuan lain. Saat menggunakan `UNORDERED_ACKNOWLEDGE` mode, semua pesan yang diterima harus diakui secara individual dan eksplisit oleh klien, terlepas dari pesanan penerimaan mereka. Untuk melakukan ini, buat sesi dengan `UNORDERED_ACKNOWLEDGE` mode.

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

Langkah-langkah yang tersisa identik dengan yang ada di [Menggunakan mode pengakuan klien](#using-client-acknowledge-mode) contoh. Untuk contoh lengkap konsumen sinkron dengan `UNORDERED_ACKNOWLEDGE` mode, lihat`SyncMessageReceiverUnorderedAcknowledge.java`.

Dalam contoh ini, outputnya terlihat mirip dengan yang berikut:

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

# Menggunakan Java Message Service dengan klien Amazon SQS lainnya
<a name="sqs-jms-client-with-sqs-clients"></a>

Menggunakan Amazon SQS Java Message Service (JMS) Client dengan AWS SDK membatasi ukuran pesan Amazon SQS hingga 256 KB. Namun, Anda dapat membuat penyedia JMS menggunakan klien Amazon SQS apa pun. Misalnya, Anda dapat menggunakan Klien JMS dengan Amazon SQS Extended Client Library for Java untuk mengirim pesan Amazon SQS yang berisi referensi ke payload pesan (hingga 2 GB) di Amazon S3. Untuk informasi selengkapnya, lihat [Mengelola pesan Amazon SQS besar menggunakan Java dan Amazon S3](sqs-s3-messages.md).

Contoh kode Java berikut menciptakan penyedia JMS untuk Extended Client Library.

Lihat prasyarat [Prasyarat untuk bekerja dengan JMS dan Amazon SQS](prerequisites.md) sebelum menguji contoh ini.

```
AmazonS3 s3 = new AmazonS3Client(credentials);
Region s3Region = Region.getRegion(Regions.US_WEST_2);
s3.setRegion(s3Region);
 
// Set the Amazon S3 bucket name, and set a lifecycle rule on the bucket to
// permanently delete objects a certain number of days after each object's creation date.
// Next, create the bucket, and enable message objects to be stored in the bucket.
BucketLifecycleConfiguration.Rule expirationRule = new BucketLifecycleConfiguration.Rule();
expirationRule.withExpirationInDays(14).withStatus("Enabled");
BucketLifecycleConfiguration lifecycleConfig = new BucketLifecycleConfiguration().withRules(expirationRule);
 
s3.createBucket(s3BucketName);
s3.setBucketLifecycleConfiguration(s3BucketName, lifecycleConfig);
System.out.println("Bucket created and configured.");

// Set the SQS extended client configuration with large payload support enabled.
ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration()
    .withLargePayloadSupportEnabled(s3, s3BucketName);
 
AmazonSQS sqsExtended = new AmazonSQSExtendedClient(new AmazonSQSClient(credentials), extendedClientConfig);
Region sqsRegion = Region.getRegion(Regions.US_WEST_2);
sqsExtended.setRegion(sqsRegion);
```

Contoh kode Java berikut membuat pabrik koneksi:

```
// Create the connection factory using the environment variable credential provider.
// Pass the configured Amazon SQS Extended Client to the JMS connection factory.
SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
        new ProviderConfiguration(),
        sqsExtended
        );
 
// Create the connection.
SQSConnection connection = connectionFactory.createConnection();
```

# Contoh Java yang berfungsi untuk menggunakan JMS dengan antrian standar Amazon SQS
<a name="sqs-jms-code-examples"></a>

Contoh kode berikut menunjukkan cara menggunakan Java Message Service (JMS) dengan antrian standar Amazon SQS. Untuk informasi lebih lanjut tentang bekerja dengan antrian FIFO, lihat[Untuk membuat antrian FIFO](getting-started.md#creating-queue-FIFO),, dan. [Mengirim pesan secara sinkron](getting-started.md#send-messages-synchronously) [Menerima pesan secara sinkron](getting-started.md#receive-messages-synchronously) (Menerima pesan secara sinkron sama untuk antrian standar dan FIFO. Namun, pesan dalam antrian FIFO berisi lebih banyak atribut.)

Lihat prasyarat [Prasyarat untuk bekerja dengan JMS dan Amazon SQS](prerequisites.md) sebelum menguji contoh berikut.

## ExampleConfiguration.jawa
<a name="example-configuration"></a>

Contoh kode Java SDK v 1.x berikut menetapkan nama antrian default, wilayah, dan kredenal yang akan digunakan dengan contoh Java lainnya.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class ExampleConfiguration {
    public static final String DEFAULT_QUEUE_NAME = "SQSJMSClientExampleQueue";
    
    public static final Region DEFAULT_REGION = Region.getRegion(Regions.US_EAST_2);
    
    private static String getParameter( String args[], int i ) {
        if( i + 1 >= args.length ) {
            throw new IllegalArgumentException( "Missing parameter for " + args[i] );
        }
        return args[i+1];
    }
    
    /**
     * Parse the command line and return the resulting config. If the config parsing fails
     * print the error and the usage message and then call System.exit
     * 
     * @param app the app to use when printing the usage string
     * @param args the command line arguments
     * @return the parsed config
     */
    public static ExampleConfiguration parseConfig(String app, String args[]) {
        try {
            return new ExampleConfiguration(args);
        } catch (IllegalArgumentException e) {
            System.err.println( "ERROR: " + e.getMessage() );
            System.err.println();
            System.err.println( "Usage: " + app + " [--queue <queue>] [--region <region>] [--credentials <credentials>] ");
            System.err.println( "  or" );
            System.err.println( "       " + app + " <spring.xml>" );
            System.exit(-1);
            return null;
        }
    }
    
    private ExampleConfiguration(String args[]) {
        for( int i = 0; i < args.length; ++i ) {
            String arg = args[i];
            if( arg.equals( "--queue" ) ) {
                setQueueName(getParameter(args, i));
                i++;
            } else if( arg.equals( "--region" ) ) {
                String regionName = getParameter(args, i);
                try {
                    setRegion(Region.getRegion(Regions.fromName(regionName)));
                } catch( IllegalArgumentException e ) {
                    throw new IllegalArgumentException( "Unrecognized region " + regionName );  
                }
                i++;
            } else if( arg.equals( "--credentials" ) ) {
                String credsFile = getParameter(args, i);
                try {
                    setCredentialsProvider( new PropertiesFileCredentialsProvider(credsFile) );
                } catch (AmazonClientException e) {
                    throw new IllegalArgumentException("Error reading credentials from " + credsFile, e );
                }
                i++;
            } else {
                throw new IllegalArgumentException("Unrecognized option " + arg);
            }
        }
    }
    
    private String queueName = DEFAULT_QUEUE_NAME;
    private Region region = DEFAULT_REGION;
    private AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    
    public String getQueueName() {
        return queueName;
    }
    
    public void setQueueName(String queueName) {
        this.queueName = queueName;
    }
    
    public Region getRegion() {
        return region;
    }
    
    public void setRegion(Region region) {
        this.region = region;
    }
 
    public AWSCredentialsProvider getCredentialsProvider() {
        return credentialsProvider;
    }
    
    public void setCredentialsProvider(AWSCredentialsProvider credentialsProvider) {
        // Make sure they're usable first
        credentialsProvider.getCredentials();
        this.credentialsProvider = credentialsProvider;
    }
}
```

## TextMessageSender.jawa
<a name="example-sender"></a>

Contoh kode Java berikut menciptakan produser pesan teks.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class TextMessageSender {
    public static void main(String args[]) throws JMSException {
        ExampleConfiguration config = ExampleConfiguration.parseConfig("TextMessageSender", args);
        
        ExampleCommon.setupLogging();
        
        // Create the connection factory based on the config       
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
        
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
        
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
            
        // Create the session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer( session.createQueue( config.getQueueName() ) );
        
        sendMessages(session, producer);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println( "Connection closed" );
    }
 
    private static void sendMessages( Session session, MessageProducer producer ) {
        BufferedReader inputReader = new BufferedReader(
            new InputStreamReader( System.in, Charset.defaultCharset() ) );
        
        try {
            String input;
            while( true ) { 
                System.out.print( "Enter message to send (leave empty to exit): " );
                input = inputReader.readLine();
                if( input == null || input.equals("" ) ) break;
                
                TextMessage message = session.createTextMessage(input);
                producer.send(message);
                System.out.println( "Send message " + message.getJMSMessageID() );
            }
        } catch (EOFException e) {
            // Just return on EOF
        } catch (IOException e) {
            System.err.println( "Failed reading input: " + e.getMessage() );
        } catch (JMSException e) {
            System.err.println( "Failed sending message: " + e.getMessage() );
            e.printStackTrace();
        }
    }
}
```

## SyncMessageReceiver.jawa
<a name="example-synchronous-message-receiver"></a>

Contoh kode Java berikut menciptakan konsumen pesan sinkron.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class SyncMessageReceiver {
public static void main(String args[]) throws JMSException {
    ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiver", args);
    
    ExampleCommon.setupLogging();
    
    // Create the connection factory based on the config
    SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
            new ProviderConfiguration(),
            AmazonSQSClientBuilder.standard()
                    .withRegion(config.getRegion().getName())
                    .withCredentials(config.getCredentialsProvider())
            );
    
    // Create the connection
    SQSConnection connection = connectionFactory.createConnection();
    
    // Create the queue if needed
    ExampleCommon.ensureQueueExists(connection, config.getQueueName());
        
    // Create the session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) );

    connection.start();
    
    receiveMessages(session, consumer);

    // Close the connection. This closes the session automatically
    connection.close();
    System.out.println( "Connection closed" );
}

private static void receiveMessages( Session session, MessageConsumer consumer ) {
    try {
        while( true ) {
            System.out.println( "Waiting for messages");
            // Wait 1 minute for a message
            Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1));
            if( message == null ) {
                System.out.println( "Shutting down after 1 minute of silence" );
                break;
            }
            ExampleCommon.handleMessage(message);
            message.acknowledge();
            System.out.println( "Acknowledged message " + message.getJMSMessageID() );
        }
    } catch (JMSException e) {
        System.err.println( "Error receiving from SQS: " + e.getMessage() );
        e.printStackTrace();
    }
}
}
```

## AsyncMessageReceiver.jawa
<a name="example-asynchronous-message-receiver"></a>

Contoh kode Java berikut menciptakan konsumen pesan asinkron.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class AsyncMessageReceiver {
    public static void main(String args[]) throws JMSException, InterruptedException {
        ExampleConfiguration config = ExampleConfiguration.parseConfig("AsyncMessageReceiver", args);
         
        ExampleCommon.setupLogging();          
         
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
         
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
         
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
             
        // Create the session
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) );
         
        // No messages are processed until this is called
        connection.start();

        ReceiverCallback callback = new ReceiverCallback();
        consumer.setMessageListener( callback );
         
        callback.waitForOneMinuteOfSilence();
        System.out.println( "Returning after one minute of silence" );

        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println( "Connection closed" );
    }
    
    
    private static class ReceiverCallback implements MessageListener {
        // Used to listen for message silence
        private volatile long timeOfLastMessage = System.nanoTime();
         
        public void waitForOneMinuteOfSilence() throws InterruptedException {
            for(;;) {
                long timeSinceLastMessage = System.nanoTime() - timeOfLastMessage;
                long remainingTillOneMinuteOfSilence = 
                    TimeUnit.MINUTES.toNanos(1) - timeSinceLastMessage;
                if( remainingTillOneMinuteOfSilence < 0 ) {
                    break;
                }
                TimeUnit.NANOSECONDS.sleep(remainingTillOneMinuteOfSilence);
            }
        }
         

        @Override
        public void onMessage(Message message) {
            try {
                ExampleCommon.handleMessage(message);
                message.acknowledge();
                System.out.println( "Acknowledged message " + message.getJMSMessageID() );
                timeOfLastMessage = System.nanoTime();
            } catch (JMSException e) {
                System.err.println( "Error processing message: " + e.getMessage() );
                e.printStackTrace();
            }
        }
    }
}
```

## SyncMessageReceiverClientAcknowledge.jawa
<a name="example-synchronous-receiver-client-acknowledge-mode"></a>

Contoh kode Java berikut menciptakan konsumen sinkron dengan modus mengakui klien.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

/**
 * An example class to demonstrate the behavior of CLIENT_ACKNOWLEDGE mode for received messages. This example
 * complements the example given in {@link SyncMessageReceiverUnorderedAcknowledge} for UNORDERED_ACKNOWLEDGE mode.
 *
 * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages
 * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to
 * receive another message is made. It's shown that no message is returned for this attempt since in CLIENT_ACKNOWLEDGE mode,
 * as expected, all the messages prior to the acknowledged messages are also acknowledged.
 *
 * This ISN'T the behavior for UNORDERED_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverUnorderedAcknowledge}
 * for an example.
 */
public class SyncMessageReceiverClientAcknowledge {
 
    // Visibility time-out for the queue. It must match to the one set for the queue for this example to work.
    private static final long TIME_OUT_SECONDS = 1;
 
    public static void main(String args[]) throws JMSException, InterruptedException {
        // Create the configuration for the example
        ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverClientAcknowledge", args);
 
        // Setup logging for the example
        ExampleCommon.setupLogging();
 
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
 
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
 
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
 
        // Create the session  with client acknowledge mode
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
 
        // Create the producer and consume
        MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName()));
        MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName()));
 
        // Open the connection
        connection.start();
 
        // Send two text messages
        sendMessage(producer, session, "Message 1");
        sendMessage(producer, session, "Message 2");
 
        // Receive a message and don't acknowledge it
        receiveMessage(consumer, false);
 
        // Receive another message and acknowledge it
        receiveMessage(consumer, true);
 
        // Wait for the visibility time out, so that unacknowledged messages reappear in the queue
        System.out.println("Waiting for visibility timeout...");
        Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        // Attempt to receive another message and acknowledge it. This results in receiving no messages since
        // we have acknowledged the second message. Although we didn't explicitly acknowledge the first message,
        // in the CLIENT_ACKNOWLEDGE mode, all the messages received prior to the explicitly acknowledged message
        // are also acknowledged. Therefore, we have implicitly acknowledged the first message.
        receiveMessage(consumer, true);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println("Connection closed.");
    }
 
    /**
     * Sends a message through the producer.
     *
     * @param producer Message producer
     * @param session Session
     * @param messageText Text for the message to be sent
     * @throws JMSException
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it
        producer.send(session.createTextMessage(messageText));
    }
 
    /**
     * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS).
     * If a message is received, the message is printed. If no message is received, "Queue is empty!" is
     * printed.
     *
     * @param consumer Message consumer
     * @param acknowledge If true and a message is received, the received message is acknowledged.
     * @throws JMSException
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message
        Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        if (message == null) {
            System.out.println("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text
            System.out.println("Received: " + ((TextMessage) message).getText());
 
            // Acknowledge the message if asked
            if (acknowledge) message.acknowledge();
        }
    }
}
```

## SyncMessageReceiverUnorderedAcknowledge.jawa
<a name="example-synchronous-receiver-unordered-acknowledge-mode"></a>

Contoh kode Java berikut menciptakan konsumen sinkron dengan modus mengakui tidak berurutan.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

/**
 * An example class to demonstrate the behavior of UNORDERED_ACKNOWLEDGE mode for received messages. This example
 * complements the example given in {@link SyncMessageReceiverClientAcknowledge} for CLIENT_ACKNOWLEDGE mode.
 *
 * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages
 * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to
 * receive another message is made. It's shown that the first message received in the prior attempt is returned again
 * for the second attempt. In UNORDERED_ACKNOWLEDGE mode, all the messages must be explicitly acknowledged no matter what
 * the order they're received.
 *
 * This ISN'T the behavior for CLIENT_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverClientAcknowledge}
 * for an example.
 */
public class SyncMessageReceiverUnorderedAcknowledge {
 
    // Visibility time-out for the queue. It must match to the one set for the queue for this example to work.
    private static final long TIME_OUT_SECONDS = 1;
 
    public static void main(String args[]) throws JMSException, InterruptedException {
        // Create the configuration for the example
        ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverUnorderedAcknowledge", args);
 
        // Setup logging for the example
        ExampleCommon.setupLogging();
 
        // Create the connection factory based on the config
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                AmazonSQSClientBuilder.standard()
                        .withRegion(config.getRegion().getName())
                        .withCredentials(config.getCredentialsProvider())
                );
 
        // Create the connection
        SQSConnection connection = connectionFactory.createConnection();
 
        // Create the queue if needed
        ExampleCommon.ensureQueueExists(connection, config.getQueueName());
 
        // Create the session  with unordered acknowledge mode
        Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE);
 
        // Create the producer and consume
        MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName()));
        MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName()));
 
        // Open the connection
        connection.start();
 
        // Send two text messages
        sendMessage(producer, session, "Message 1");
        sendMessage(producer, session, "Message 2");
 
        // Receive a message and don't acknowledge it
        receiveMessage(consumer, false);
 
        // Receive another message and acknowledge it
        receiveMessage(consumer, true);
 
        // Wait for the visibility time out, so that unacknowledged messages reappear in the queue
        System.out.println("Waiting for visibility timeout...");
        Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        // Attempt to receive another message and acknowledge it. This results in receiving the first message since
        // we have acknowledged only the second message. In the UNORDERED_ACKNOWLEDGE mode, all the messages must
        // be explicitly acknowledged.
        receiveMessage(consumer, true);
 
        // Close the connection. This closes the session automatically
        connection.close();
        System.out.println("Connection closed.");
    }
 
    /**
     * Sends a message through the producer.
     *
     * @param producer Message producer
     * @param session Session
     * @param messageText Text for the message to be sent
     * @throws JMSException
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it
        producer.send(session.createTextMessage(messageText));
    }
 
    /**
     * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS).
     * If a message is received, the message is printed. If no message is received, "Queue is empty!" is
     * printed.
     *
     * @param consumer Message consumer
     * @param acknowledge If true and a message is received, the received message is acknowledged.
     * @throws JMSException
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message
        Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS));
 
        if (message == null) {
            System.out.println("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text
            System.out.println("Received: " + ((TextMessage) message).getText());
 
            // Acknowledge the message if asked
            if (acknowledge) message.acknowledge();
        }
    }
}
```

## SpringExampleConfiguration.xml.xl
<a name="example-spring-configuration"></a>

Contoh kode XHTML berikut adalah file konfigurasi kacang untuk[SpringExample.jawa](#example-spring).

```
<!--
    Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.

    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    https://aws.amazon.com/apache2.0

    or in the "license" file accompanying this file. This file is distributed
    on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
    express or implied. See the License for the specific language governing
    permissions and limitations under the License.
-->

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
    ">
    
    <bean id="CredentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain"/>
    
    <bean id="ClientBuilder" class="com.amazonaws.services.sqs.AmazonSQSClientBuilder" factory-method="standard">
        <property name="region" value="us-east-2"/>
        <property name="credentials" ref="CredentialsProviderBean"/>               
    </bean>
    
    <bean id="ProviderConfiguration" class="com.amazon.sqs.javamessaging.ProviderConfiguration">
        <property name="numberOfMessagesToPrefetch" value="5"/>
    </bean>
    
    <bean id="ConnectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory">
        <constructor-arg ref="ProviderConfiguration" />
        <constructor-arg ref="ClientBuilder" />
    </bean>
    
    <bean id="Connection" class="javax.jms.Connection"
        factory-bean="ConnectionFactory"
        factory-method="createConnection"
        init-method="start"
        destroy-method="close" />
    
    <bean id="QueueName" class="java.lang.String">
        <constructor-arg value="SQSJMSClientExampleQueue"/>
    </bean>
</beans>
```

## SpringExample.jawa
<a name="example-spring"></a>

Contoh kode Java berikut menggunakan file konfigurasi bean untuk menginisialisasi objek Anda.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */
                
public class SpringExample {
    public static void main(String args[]) throws JMSException {
        if( args.length != 1 || !args[0].endsWith(".xml")) {
            System.err.println( "Usage: " + SpringExample.class.getName() + " <spring config.xml>" );
            System.exit(1);
        }
        
        File springFile = new File( args[0] );
        if( !springFile.exists() || !springFile.canRead() ) {
            System.err.println( "File " + args[0] + " doesn't exist or isn't readable.");
            System.exit(2);
        }
        
        ExampleCommon.setupLogging();
        
        FileSystemXmlApplicationContext context = 
            new FileSystemXmlApplicationContext( "file://" + springFile.getAbsolutePath() );
        
        Connection connection;
        try {
            connection = context.getBean(Connection.class);
        } catch( NoSuchBeanDefinitionException e ) {
            System.err.println( "Can't find the JMS connection to use: " + e.getMessage() );
            System.exit(3);
            return;
        }
        
        String queueName;
        try {
            queueName = context.getBean("QueueName", String.class);
        } catch( NoSuchBeanDefinitionException e ) {
            System.err.println( "Can't find the name of the queue to use: " + e.getMessage() );
            System.exit(3);
            return;
        }
        
        if( connection instanceof SQSConnection ) {
            ExampleCommon.ensureQueueExists( (SQSConnection) connection, queueName );
        }
        
        // Create the session
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer( session.createQueue( queueName) );
        
        receiveMessages(session, consumer);
 
        // The context can be setup to close the connection for us
        context.close();
        System.out.println( "Context closed" );
    }
 
    private static void receiveMessages( Session session, MessageConsumer consumer ) {
        try {
            while( true ) {
                System.out.println( "Waiting for messages");
                // Wait 1 minute for a message
                Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1));
                if( message == null ) {
                    System.out.println( "Shutting down after 1 minute of silence" );
                    break;
                }
                ExampleCommon.handleMessage(message);
                message.acknowledge();
                System.out.println( "Acknowledged message" );
            }
        } catch (JMSException e) {
            System.err.println( "Error receiving from SQS: " + e.getMessage() );
            e.printStackTrace();
        }
    }
}
```

## ExampleCommon.jawa
<a name="example-common"></a>

Contoh kode Java berikut memeriksa apakah antrian Amazon SQS ada dan kemudian membuatnya jika tidak. Ini juga termasuk contoh kode logging.

```
/*
 * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  https://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

public class ExampleCommon {
    /**
     * A utility function to check the queue exists and create it if needed. For most  
     * use cases this is usually done by an administrator before the application is run. 
     */
    public static void ensureQueueExists(SQSConnection connection, String queueName) throws JMSException {
        AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();
        
        /**
         * In most cases, you can do this with just a createQueue call, but GetQueueUrl 
         * (called by queueExists) is a faster operation for the common case where the queue 
         * already exists. Also many users and roles have permission to call GetQueueUrl
         * but don't have permission to call CreateQueue.
         */
        if( !client.queueExists(queueName) ) {
            client.createQueue( queueName );
        }
    }
 
    public static void setupLogging() {
        // Setup logging
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.WARN);
    }
 
    public static void handleMessage(Message message) throws JMSException {
        System.out.println( "Got message " + message.getJMSMessageID() );
        System.out.println( "Content: ");
        if( message instanceof TextMessage ) {
            TextMessage txtMessage = ( TextMessage ) message;
            System.out.println( "\t" + txtMessage.getText() );
        } else if( message instanceof BytesMessage ){
            BytesMessage byteMessage = ( BytesMessage ) message;
            // Assume the length fits in an int - SQS only supports sizes up to 256k so that
            // should be true
            byte[] bytes = new byte[(int)byteMessage.getBodyLength()];
            byteMessage.readBytes(bytes);
            System.out.println( "\t" +  Base64.encodeAsString( bytes ) );
        } else if( message instanceof ObjectMessage ) {
            ObjectMessage objMessage = (ObjectMessage) message;
            System.out.println( "\t" + objMessage.getObject() );
        }
    }
}
```

# Amazon SQS mendukung implementasi JMS 1.1
<a name="supported-implementations"></a>

Amazon SQS Java Messaging Library mendukung implementasi [JMS 1.1](http://docs.oracle.com/javaee/6/api/javax/jms/package-summary.html) berikut. Untuk informasi selengkapnya tentang fitur dan kemampuan yang didukung dari Amazon SQS Java Messaging Library, lihat FAQ [Amazon SQS](https://aws.amazon.com/sqs/faqs/).

## Antarmuka umum yang didukung
<a name="supported-common-interfaces"></a>
+ `Connection`
+ `ConnectionFactory`
+ `Destination`
+ `Session`
+ `MessageConsumer`
+ `MessageProducer`

## Jenis pesan yang didukung
<a name="supported-message-types"></a>
+ `ByteMessage`
+ `ObjectMessage`
+ `TextMessage`

## Mode pengakuan pesan yang didukung
<a name="supported-message-acknowledgement-modes"></a>
+ `AUTO_ACKNOWLEDGE`
+ `CLIENT_ACKNOWLEDGE`
+ `DUPS_OK_ACKNOWLEDGE`
+ `UNORDERED_ACKNOWLEDGE`

**catatan**  
`UNORDERED_ACKNOWLEDGE`Mode ini bukan bagian dari spesifikasi JMS 1.1. Mode ini membantu Amazon SQS mengizinkan klien JMS untuk secara eksplisit mengakui pesan.

## Header yang ditentukan JMS dan properti yang dicadangkan
<a name="jms-defined-headers-reserved-properties"></a>

### Untuk mengirim pesan
<a name="for-sending-messages"></a>

Saat mengirim pesan, Anda dapat mengatur header dan properti berikut untuk setiap pesan:
+ `JMSXGroupID`(diperlukan untuk antrian FIFO, tidak diperbolehkan untuk antrian standar)
+ `JMS_SQS_DeduplicationId`(opsional untuk antrian FIFO, tidak diperbolehkan untuk antrian standar)

Setelah Anda mengirim pesan, Amazon SQS menetapkan header dan properti berikut untuk setiap pesan:
+ `JMSMessageID`
+ `JMS_SQS_SequenceNumber`(hanya untuk antrian FIFO)

### Untuk menerima pesan
<a name="for-receiving-messages"></a>

Saat Anda menerima pesan, Amazon SQS menetapkan header dan properti berikut untuk setiap pesan:
+ `JMSDestination`
+ `JMSMessageID`
+ `JMSRedelivered`
+ `JMSXDeliveryCount`
+ `JMSXGroupID`(hanya untuk antrian FIFO)
+ `JMS_SQS_DeduplicationId`(hanya untuk antrian FIFO)
+ `JMS_SQS_SequenceNumber`(hanya untuk antrian FIFO)