RammusXu / rammusxu.github.io

My profile
https://rammusxu.github.io/
2 stars 0 forks source link

在Intellij IDE上使用aws-java-sdk #26

Closed RammusXu closed 7 years ago

RammusXu commented 8 years ago

開新專案

https://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-project-gradle.html

To configure the SDK for Gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "io.spring.gradle:dependency-management-plugin:0.5.4.RELEASE"
    }
}
apply plugin: "io.spring.dependency-management"
dependencyManagement {
    imports {
        mavenBom 'com.amazonaws:aws-java-sdk-bom:1.10.47'
    }
}
dependencies {
    compile 'com.amazonaws:aws-java-sdk-s3'
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

Gradle will automatically resolve the correct version of your SDK dependencies using the information from the BOM.

RammusXu commented 8 years ago

Issues

遇到IDE提示Cannot resolve symbol 'imports'

2016-08-12 5 49 02 解決方法 http://stackoverflow.com/questions/5905896/intellij-inspection-gives-cannot-resolve-symbol-but-still-compiles-code

RammusXu commented 8 years ago

步驟

1. 將 receiveMessage() 包成 TimerTask

public static class ReceiveTask extends TimerTask {
        public void run() {
            ...
        }
}

2. 在 Main() 使用 Timer 做排程,每次 polling message 後等待 2 秒再繼續 polling

        Timer timer = new Timer();
        TimerTask receiveTask = new ReceiveTask();

        timer.schedule(receiveTask, 1000, 2000);

SQS snippet

package com.haufu.aws;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.*;

import java.util.*;

/**
 * Created by rammus on 2016/8/12.
 */
public class Main {
    private static AmazonSQS sqs;
    private static String myQueueUrl;
    private static boolean deleteMessageFlag = false;
    private static AWSCredentials credentials;

    public static void main(String[] args) {
        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (~/.aws/credentials).
         */
        try {
            credentials = new ProfileCredentialsProvider().getCredentials();

            sqs = new AmazonSQSClient(credentials);
            Region myRegion = Region.getRegion(Regions.AP_NORTHEAST_1);
            sqs.setRegion(myRegion);

            // Create a queue
            System.out.println("Creating a new SQS queue called MyQueue.\n");
            CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
            myQueueUrl = sqs.getQueueUrl("RD_RAMMUS_DEV").getQueueUrl();
//          myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Cannot load the credentials from the credential profiles file. " +
                            "Please make sure that your credentials file is at the correct " +
                            "location (~/.aws/credentials), and is in valid format.",
                    e);
        }

        Timer timer = new Timer();
        TimerTask receiveTask = new ReceiveTask();

        timer.schedule(receiveTask, 1000, 2000);
        sendMessage();

        System.out.println("===========================================");
        System.out.println("Getting Started with Amazon SQS");
        System.out.println("===========================================\n");

    }

    public static void sendMessage() {
        // Send a message
        System.out.format("Sending a message to %s.\n", myQueueUrl);
        sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));
    }

    public static void listQueue() {
        // List queues
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }
        System.out.println();
    }

    public static void deleteQueue() {
        // Delete a queue
        System.out.println("Deleting the test queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    }

    public static class ReceiveTask extends TimerTask {
        public void run() {
            System.out.println(new Date());
            try {
                // Receive messages
                System.out.println("Receiving messages from MyQueue.\n");
                ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
                receiveMessageRequest.setMaxNumberOfMessages(5);
//              receiveMessageRequest.setWaitTimeSeconds(3);

                List<Message> messages = sqs.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 (Map.Entry<String, String> entry : message.getAttributes().entrySet()) {
                        System.out.println("  Attribute");
                        System.out.println("    Name:  " + entry.getKey());
                        System.out.println("    Value: " + entry.getValue());
                    }

                    if (deleteMessageFlag) {
                        // Delete a message
                        System.out.println("Deleting a message.\n");
                        String messageReceiptHandle = messages.get(0).getReceiptHandle();
                        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));
                    }
                }
                System.out.println();

            } catch (AmazonServiceException ase) {
                System.out.println("Caught an AmazonServiceException, which means your request made it " +
                        "to Amazon SQS, but was rejected with an error response for some reason.");
                System.out.println("Error Message:    " + ase.getMessage());
                System.out.println("HTTP Status Code: " + ase.getStatusCode());
                System.out.println("AWS Error Code:   " + ase.getErrorCode());
                System.out.println("Error Type:       " + ase.getErrorType());
                System.out.println("Request ID:       " + ase.getRequestId());
            } catch (AmazonClientException ace) {
                System.out.println("Caught an AmazonClientException, which means the client encountered " +
                        "a serious internal problem while trying to communicate with SQS, such as not " +
                        "being able to access the network.");
                System.out.println("Error Message: " + ace.getMessage());
            }
        }
    }

}