AWS SDK 예제 GitHub 리포지토리에 더 많은 AWS문서 SDK 예제가 있습니다.
AWS SDK를 사용한 Neptune 코드 예제
다음 코드 예제에서는 Amazon Neptune을 AWS 소프트웨어 개발 키트(SDK)와 함께 사용하는 방법을 보여줍니다.
기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.
작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.
시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.
시작
다음 코드 예제에서는 Neptune 사용을 시작하는 방법을 보여줍니다.
- Java
-
- SDK for Java 2.x
-
GitHub에 더 많은 내용이 있습니다. AWS코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class HelloNeptune {
public static void main(String[] args) {
NeptuneAsyncClient neptuneClient = NeptuneAsyncClient.create();
describeDbCluster(neptuneClient).join(); // This ensures the async code runs to completion
}
/**
* Describes the Amazon Neptune DB clusters.
*
* @param neptuneClient the Neptune asynchronous client used to make the request
* @return a {@link CompletableFuture} that completes when the operation is finished
*/
public static CompletableFuture<Void> describeDbCluster(NeptuneAsyncClient neptuneClient) {
DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
.maxRecords(20)
.build();
SdkPublisher<DescribeDbClustersResponse> paginator = neptuneClient.describeDBClustersPaginator(request);
CompletableFuture<Void> future = new CompletableFuture<>();
paginator.subscribe(new Subscriber<DescribeDbClustersResponse>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription s) {
this.subscription = s;
s.request(Long.MAX_VALUE); // request all items
}
@Override
public void onNext(DescribeDbClustersResponse response) {
response.dbClusters().forEach(cluster -> {
System.out.println("Cluster Identifier: " + cluster.dbClusterIdentifier());
System.out.println("Status: " + cluster.status());
});
}
@Override
public void onError(Throwable t) {
future.completeExceptionally(t);
}
@Override
public void onComplete() {
future.complete(null);
}
});
return future.whenComplete((result, throwable) -> {
neptuneClient.close();
if (throwable != null) {
System.err.println("Error describing DB clusters: " + throwable.getMessage());
}
});
}
- Python
-
- SDK for Python (Boto3)
-
GitHub에 더 많은 내용이 있습니다. AWS코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
import boto3
from botocore.exceptions import ClientError
def describe_db_clusters(neptune_client):
"""
Describes the Amazon Neptune DB clusters using a paginator to handle multiple pages.
Raises ClientError with 'ResourceNotFoundException' if no clusters are found.
"""
paginator = neptune_client.get_paginator("describe_db_clusters")
clusters_found = False
for page in paginator.paginate():
for cluster in page.get("DBClusters", []):
clusters_found = True
print(f"Cluster Identifier: {cluster['DBClusterIdentifier']}")
print(f"Status: {cluster['Status']}")
if not clusters_found:
raise ClientError(
{
"Error": {
"Code": "ResourceNotFoundException",
"Message": "No Neptune DB clusters found."
}
},
operation_name="DescribeDBClusters"
)
def main():
"""
Main entry point: creates the Neptune client and calls the describe operation.
"""
neptune_client = boto3.client("neptune")
try:
describe_db_clusters(neptune_client)
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code == "ResourceNotFoundException":
print(f"Resource not found: {e.response['Error']['Message']}")
else:
print(f"Unexpected ClientError: {e.response['Error']['Message']}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
if __name__ == "__main__":
main()