AWS SQS (Simple Queue Service)を使ってみる(Java)

| コメントをどうぞ

AWS SQS (Simple Queue Service)を試してみた。

事前準備として、AwsCredentials.propertiesをクラスと同じディレクトリに置き、accessKeyとsecretKeyを設定しておきます。

キューの作成

MyQueueというキューを作成する。

import java.io.IOException;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueRequest;

public class CreateQueue {
    static AmazonSQSClient client;

    public static void main(String[] args) throws Exception {
        try {
            createClient();
            CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
            String myQueueUrl = client.createQueue(createQueueRequest).getQueueUrl();
            System.out.println("Created: " + myQueueUrl);
            System.out.println("Listing all queues in your account.");
            for (String queueUrl : client.listQueues().getQueueUrls()) {
                System.out.println("  QueueUrl: " + queueUrl);
            }
            System.out.println();
        }  
        catch (AmazonServiceException ase) {
            System.err.println(ase.getMessage());
        }  
    }

    private static void createClient() throws IOException {
        AWSCredentials credentials = new PropertiesCredentials(
                CreateQueue.class.getResourceAsStream("AwsCredentials.properties"));
        client = new AmazonSQSClient(credentials);
        Region apNortheast1 = Region.getRegion(Regions.AP_NORTHEAST_1);
        client.setRegion(apNortheast1);
    }
}

実行結果はこちら

Created: https://sqs.ap-northeast-1.amazonaws.com/xxx/MyQueue
Listing all queues in your account.
  QueueUrl: https://sqs.ap-northeast-1.amazonaws.com/xxx/MyQueue

AWS管理コンソールから確認するとMyQueueが出来ています。
aws-sqs1

メッセージの送信

MyQueueへメッセージを送信する。

import java.io.IOException;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageResult;

public class SendMessage {
    static AmazonSQSClient client;

    public static void main(String[] args) throws Exception {
        try {
            createClient();
            String myQueueUrl = client.getQueueUrl("MyQueue").getQueueUrl();
            System.out.println("Sending a message to MyQueue.");
            String msg = "This is my message text.";
            SendMessageResult result = client.sendMessage(new SendMessageRequest(myQueueUrl, msg));
            System.out.println(result);
        }  
        catch (AmazonServiceException ase) {
            System.err.println(ase.getMessage());
        }  
    }

    private static void createClient() throws IOException {
        AWSCredentials credentials = new PropertiesCredentials(
                SendMessage.class.getResourceAsStream("AwsCredentials.properties"));
        client = new AmazonSQSClient(credentials);
        Region apNortheast1 = Region.getRegion(Regions.AP_NORTHEAST_1);
        client.setRegion(apNortheast1);
    }
}

3回実行した結果はこちら

Sending a message to MyQueue.
{MD5OfMessageBody: 6a1559560f67c5e7a7d5d838bf0272ee,MessageId: b2176ccd-5aff-4c5a-b6ba-021a66ac2d51}

Sending a message to MyQueue.
{MD5OfMessageBody: 6a1559560f67c5e7a7d5d838bf0272ee,MessageId: 8ca46d4e-929d-44cf-a35e-8553cfe234e1}

Sending a message to MyQueue.
{MD5OfMessageBody: 6a1559560f67c5e7a7d5d838bf0272ee,MessageId: 8f6ed142-c445-4fd4-b267-0f2a24a6a04b}

メッセージの受信

MyQueueからメッセージを受信する。

import java.io.IOException;
import java.util.List;
import java.util.Map.Entry;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;

public class ReceiveMessage {
    static AmazonSQSClient client;

    public static void main(String[] args) throws Exception {
        try {
            createClient();
            String myQueueUrl = client.getQueueUrl("MyQueue").getQueueUrl();
            System.out.println("Receiving messages from MyQueue.");
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
            receiveMessageRequest.setMaxNumberOfMessages(10);
            List<Message> messages = client.receiveMessage(receiveMessageRequest).getMessages();
            for (Message message : messages) {
                System.out.println("  Message");
                System.out.println("    MessageId:     " + message.getMessageId());
                System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
                System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
                System.out.println("    Body:          " + message.getBody());
                for (Entry<String, String> entry : message.getAttributes().entrySet()) {
                    System.out.println("  Attribute");
                    System.out.println("    Name:  " + entry.getKey());
                    System.out.println("    Value: " + entry.getValue());
                }
                System.out.println("Deleting a message.");
                String messageRecieptHandle = message.getReceiptHandle();
                client.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageRecieptHandle));
            }
            System.out.println();
        }  
        catch (AmazonServiceException ase) {
            System.err.println(ase.getMessage());
        }  
    }

    private static void createClient() throws IOException {
        AWSCredentials credentials = new PropertiesCredentials(
                ReceiveMessage.class.getResourceAsStream("AwsCredentials.properties"));
        client = new AmazonSQSClient(credentials);
        Region apNortheast1 = Region.getRegion(Regions.AP_NORTHEAST_1);
        client.setRegion(apNortheast1);
    }
}

4回実行した結果はこちら

Receiving messages from MyQueue.
  Message
    MessageId:     b2176ccd-5aff-4c5a-b6ba-021a66ac2d51
    ReceiptHandle: xxx
    MD5OfBody:     6a1559560f67c5e7a7d5d838bf0272ee
    Body:          This is my message text.
Deleting a message.

Receiving messages from MyQueue.
  Message
    MessageId:     8f6ed142-c445-4fd4-b267-0f2a24a6a04b
    ReceiptHandle: xxx
    MD5OfBody:     6a1559560f67c5e7a7d5d838bf0272ee
    Body:          This is my message text.
Deleting a message.

Receiving messages from MyQueue.
  Message
    MessageId:     8ca46d4e-929d-44cf-a35e-8553cfe234e1
    ReceiptHandle: xxx
    MD5OfBody:     6a1559560f67c5e7a7d5d838bf0272ee
    Body:          This is my message text.
Deleting a message.

Receiving messages from MyQueue.

実行して気がついたのが、受信した際の順番がバラバラとなる。
メッセージIDを確認すると、送信した1番目、3番目、2番目の順番に受信した。

また、サンプルソースではListをループしているが、1件しか受信しない。
試しにreceiveMessageRequest.setMaxNumberOfMessages(10);を実行したが、変わらない。
1件づつ処理すればよいが、順番がバラバラなので使いにくい感じ。

なお、受信を4回実行したら、ブロックされることなく0件で返ってきた。
ポーリングする際には、スリープを入れながら呼び出す感じ。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>