Use the Amazon SDK for Java 2.x
After completing the steps in Setting up the SDK, you are ready to make requests to Amazon services such as Amazon S3, DynamoDB, IAM, Amazon EC2, and more.
Work with service clients
Create a service client
To make a request to an Amazon Web Service, you must first instantiate a service client
for that service by using the static factory method, builder()
. The
builder()
method returns a builder
object that allows you
to customize the service client. The fluent setter methods return the
builder
object, so that you can chain the method calls for convenience
and for more readable code. After you configure the properties you want, call the
build()
method to create the client.
As an example, the following code snippet instantiates an Ec2Client
object as a service client for Amazon EC2.
Region region = Region.US_WEST_2; Ec2Client ec2Client = Ec2Client.builder() .region(region) .build();
Note
Service clients in the SDK are thread-safe. For best performance, treat them as long-lived objects. Each client has its own connection pool resource that is released when the client is garbage collected.
A service client object is immutable, so you must create a new client for each service to which you make requests, or if you want to use a different configuration for making requests to the same service.
Specifying the Region
in the service client builder is not required
for all Amazon services; however, it is a best practice to set the Region for the API
calls you make in your applications. See Amazon
region selection for more information.
Default client configuration
The client builders have another factory method named create()
. This
method creates a service client with the default configuration. It uses the default
provider chain to load credentials and the Amazon Web Services Region. If credentials or the Region
can’t be determined from the environment that the application is running in, the call to
create
fails. See Using credentials
and Region selection for more information about
how the SDK determines the credentials and Region to use.
For example, the following code snippet instantiates a DynamoDbClient
object as a service client for Amazon DynamoDB:
DynamoDbClient dynamoDbClient = DynamoDbClient.create();
Configure service clients
To customize the configuration of a service client, use the setters on the
builder()
factory method. For convenience and to create more readable
code, chain the methods to set multiple configuration options.
The following example shows an S3Client
that is configured with several
custom settings.
ClientOverrideConfiguration clientOverrideConfiguration = ClientOverrideConfiguration.builder() .apiCallAttemptTimeout(Duration.ofSeconds(1)) .retryPolicy(RetryPolicy.builder().numRetries(10).build()) .addMetricPublisher(CloudWatchMetricPublisher.create()) .build(); Region region = Region.US_WEST_2; S3Client s3Client = S3Client.builder() .region(region) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .overrideConfiguration(clientOverrideConfiguration) .httpClientBuilder(ApacheHttpClient.builder() .proxyConfiguration(proxyConfig.build(ProxyConfiguration.builder())) .build()) .build();
Make requests
Use the service client to make requests to the corresponding Amazon Web Service.
For example, this code snippet shows how to create a RunInstancesRequest
object to create a new Amazon EC2 instance:
// Create the request by using the fluid setter methods of the request builder. RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder() .imageId(amiId) .instanceType(InstanceType.T1_MICRO) .maxCount(1) .minCount(1) .build(); // Use the configured request with the service client. RunInstancesResponse response = ec2Client.runInstances(runInstancesRequest);
Rather than create a request and pass in the instance, the SDK provides builders that you can use to create a request. With a builder you can use a Java lambda expressions to create the request 'in-line'.
The following example rewrites the previous example by using the version of the
runInstances
method that uses a builder
// Create the request by using a lambda expression. RunInstancesResponse response = ec2.runInstances(r -> r .imageId(amiId) .instanceType(InstanceType.T1_MICRO) .maxCount(1) .minCount(1));
Handle responses
You use a response handler to process the response back from the Amazon Web Service.
For example, this code snippet shows how to create a
RunInstancesResponse
object to handle the response from Amazon EC2 by
printing out the instanceId
for the new instance from the request
above:
RunInstancesResponse runInstancesResponse = ec2Client.runInstances(runInstancesRequest); System.out.println(runInstancesResponse.instances().get(0).instanceId());
Close the service client
As a best practice, you should use a service clients for multiple API service calls during the life of an application. However, if you need a service client for a one-time use or no longer need the service client, close it.
Call the close()
method when the service client is no longer needed to
free up resources.
ec2Client.close();
If you need a service client for one-time use, you can instantiate the service client
as a resource in a try
-with-resources statement. Service clients implement
the Autoclosable
interface, so the JDK automatically calls the
close()
method at the end of the statement.
The following example demonstrates how to use a service client for a one-off call.
The StsClient
that calls the Amazon Security Token Service is closed after it returns the
account ID.
import software.amazon.awssdk.services.sts.StsClient; String getAccountID() { try (StsClient stsClient = StsClient.create()) { return stsClient.getCallerIdentity().account(); } }
Handle exceptions
The SDK uses runtime (or unchecked) exceptions, providing you fine-grained control over error handling and ensuring that exception handling will scale with your application.
An SdkServiceException
SdkClientException
This code snippet demonstrates one way to handle service exceptions when you upload a file to Amazon S3. The example code catches both client and server exceptions, logs the details, and exists the application.
Region region = Region.US_WEST_2; s3Client = S3Client.builder() .region(region) .build(); try { PutObjectRequest putObjectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(key) .build(); s3Client.putObject(putObjectRequest, RequestBody.fromString("SDK for Java test")); } catch (S3Exception se) { System.err.println("Service exception thrown."); System.err.println(se.awsErrorDetails().errorMessage()); } catch (SdkClientExeption ce){ System.err.println("Client exception thrown."); System.err.println(ce.getMessage()); } finally { System.exit(1); }
See Handling exceptions for more information.
Use waiters
Some requests take time to process, such as creating a new table in DynamoDB or creating a new Amazon S3 bucket. To ensure the resource is ready before your code continues to run, use a Waiter.
For example, this code snippet creates a new table ("myTable") in DynamoDB, waits for the table to
be in an ACTIVE
status, and then prints out the response:
DynamoDbClient dynamoDbClient = DynamoDbClient.create(); DynamoDbWaiter dynamoDbWaiter = dynamoDbClient.waiter(); WaiterResponse<DescribeTableResponse> waiterResponse = dynamoDbWaiter.waitUntilTableExists(r -> r.tableName("myTable")); waiterResponse.matched().response().ifPresent(System.out::println);
See Using waiters for more information.
HTTP clients
You can change the default configuration for HTTP clients in applications you build with the Amazon SDK for Java. For information on how to configure HTTP clients and settings, see HTTP configuration.
Retries
You can change the default settings for retries in your service clients, including the
retry mode and back-off strategy. For more information, refer to the RetryPolicy
class
For more information about retries in Amazon services, see Error retries and exponential backoff in Amazon.
Timeouts
You can configure timeouts for each of your service clients using the apiCallTimeout
and the
apiCallAttemptTimeout
setters. The apiCallTimeout
setting is the amount of time to allow the
client to complete the execution of an API call. The apiCallAttemptTimeout
setting is the
amount of time to wait for the HTTP request to complete before giving up.
For more information, see apiCallTimeout
apiCallAttemptTimeout
Execution interceptors
You can write code that intercepts the execution of your API requests and responses at different
parts of the request/response lifecycle. This enables you to publish metrics, modify a request
in-flight, debug request processing, view exceptions, and more. For more information, see
the ExecutionInterceptor
interface
Additional information
-
For complete examples of the code snippets above, see Working with Amazon DynamoDB, Working with Amazon EC2, and Working with Amazon S3.