ECSExemplos da Amazon usando SDK para Java 2.x - AWS SDK for Java 2.x

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

ECSExemplos da Amazon usando SDK para Java 2.x

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for Java 2.x com a AmazonECS.

Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar funções de serviço específicas, é possível ver as ações contextualizadas em seus devidos cenários e exemplos entre serviços.

Cenários são exemplos de código que mostram como realizar uma tarefa específica chamando várias funções dentro do mesmo serviço.

Cada exemplo inclui um link para GitHub, onde você pode encontrar instruções sobre como configurar e executar o código no contexto.

Tópicos

Ações

O código de exemplo a seguir mostra como usar CreateCluster.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.ExecuteCommandConfiguration; import software.amazon.awssdk.services.ecs.model.ExecuteCommandLogging; import software.amazon.awssdk.services.ecs.model.ClusterConfiguration; import software.amazon.awssdk.services.ecs.model.CreateClusterResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.CreateClusterRequest; /** * 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 CreateCluster { public static void main(String[] args) { final String usage = """ Usage: <clusterName>\s Where: clusterName - The name of the ECS cluster to create. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); String clusterArn = createGivenCluster(ecsClient, clusterName); System.out.println("The cluster ARN is " + clusterArn); ecsClient.close(); } public static String createGivenCluster(EcsClient ecsClient, String clusterName) { try { ExecuteCommandConfiguration commandConfiguration = ExecuteCommandConfiguration.builder() .logging(ExecuteCommandLogging.DEFAULT) .build(); ClusterConfiguration clusterConfiguration = ClusterConfiguration.builder() .executeCommandConfiguration(commandConfiguration) .build(); CreateClusterRequest clusterRequest = CreateClusterRequest.builder() .clusterName(clusterName) .configuration(clusterConfiguration) .build(); CreateClusterResponse response = ecsClient.createCluster(clusterRequest); return response.cluster().clusterArn(); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para API obter detalhes, consulte CreateClusterem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar CreateService.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.AwsVpcConfiguration; import software.amazon.awssdk.services.ecs.model.NetworkConfiguration; import software.amazon.awssdk.services.ecs.model.CreateServiceRequest; import software.amazon.awssdk.services.ecs.model.LaunchType; import software.amazon.awssdk.services.ecs.model.CreateServiceResponse; import software.amazon.awssdk.services.ecs.model.EcsException; /** * 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 CreateService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceName> <securityGroups> <subnets> <taskDefinition> Where: clusterName - The name of the ECS cluster. serviceName - The name of the ECS service to create. securityGroups - The name of the security group. subnets - The name of the subnet. taskDefinition - The name of the task definition. """; if (args.length != 5) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceName = args[1]; String securityGroups = args[2]; String subnets = args[3]; String taskDefinition = args[4]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); String serviceArn = createNewService(ecsClient, clusterName, serviceName, securityGroups, subnets, taskDefinition); System.out.println("The ARN of the service is " + serviceArn); ecsClient.close(); } public static String createNewService(EcsClient ecsClient, String clusterName, String serviceName, String securityGroups, String subnets, String taskDefinition) { try { AwsVpcConfiguration vpcConfiguration = AwsVpcConfiguration.builder() .securityGroups(securityGroups) .subnets(subnets) .build(); NetworkConfiguration configuration = NetworkConfiguration.builder() .awsvpcConfiguration(vpcConfiguration) .build(); CreateServiceRequest serviceRequest = CreateServiceRequest.builder() .cluster(clusterName) .networkConfiguration(configuration) .desiredCount(1) .launchType(LaunchType.FARGATE) .serviceName(serviceName) .taskDefinition(taskDefinition) .build(); CreateServiceResponse response = ecsClient.createService(serviceRequest); return response.service().serviceArn(); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para API obter detalhes, consulte CreateServiceem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar DeleteService.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DeleteServiceRequest; import software.amazon.awssdk.services.ecs.model.EcsException; /** * 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 DeleteService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceArn>\s Where: clusterName - The name of the ECS cluster. serviceArn - The ARN of the ECS service. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); deleteSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); } public static void deleteSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { DeleteServiceRequest serviceRequest = DeleteServiceRequest.builder() .cluster(clusterName) .service(serviceArn) .build(); ecsClient.deleteService(serviceRequest); System.out.println("The Service was successfully deleted"); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte DeleteServiceem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar DescribeClusters.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DescribeClustersRequest; import software.amazon.awssdk.services.ecs.model.DescribeClustersResponse; import software.amazon.awssdk.services.ecs.model.Cluster; import software.amazon.awssdk.services.ecs.model.EcsException; import java.util.List; /** * 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 DescribeClusters { public static void main(String[] args) { final String usage = """ Usage: <clusterArn> \s Where: clusterArn - The ARN of the ECS cluster to describe. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String clusterArn = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); descCluster(ecsClient, clusterArn); } public static void descCluster(EcsClient ecsClient, String clusterArn) { try { DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder() .clusters(clusterArn) .build(); DescribeClustersResponse response = ecsClient.describeClusters(clustersRequest); List<Cluster> clusters = response.clusters(); for (Cluster cluster : clusters) { System.out.println("The cluster name is " + cluster.clusterName()); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte DescribeClustersem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar DescribeTasks.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest; import software.amazon.awssdk.services.ecs.model.DescribeTasksResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.Task; import java.util.List; /** * 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 ListTaskDefinitions { public static void main(String[] args) { final String usage = """ Usage: <clusterArn> <taskId>\s Where: clusterArn - The ARN of an ECS cluster. taskId - The task Id value. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterArn = args[0]; String taskId = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); getAllTasks(ecsClient, clusterArn, taskId); ecsClient.close(); } public static void getAllTasks(EcsClient ecsClient, String clusterArn, String taskId) { try { DescribeTasksRequest tasksRequest = DescribeTasksRequest.builder() .cluster(clusterArn) .tasks(taskId) .build(); DescribeTasksResponse response = ecsClient.describeTasks(tasksRequest); List<Task> tasks = response.tasks(); for (Task task : tasks) { System.out.println("The task ARN is " + task.taskDefinitionArn()); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte DescribeTasksem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar ListClusters.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.ListClustersResponse; import software.amazon.awssdk.services.ecs.model.EcsException; import java.util.List; /** * 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 ListClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); listAllClusters(ecsClient); ecsClient.close(); } public static void listAllClusters(EcsClient ecsClient) { try { ListClustersResponse response = ecsClient.listClusters(); List<String> clusters = response.clusterArns(); for (String cluster : clusters) { System.out.println("The cluster arn is " + cluster); } } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte ListClustersem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar UpdateService.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.ecs.model.EcsException; import software.amazon.awssdk.services.ecs.model.UpdateServiceRequest; /** * 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 UpdateService { public static void main(String[] args) { final String usage = """ Usage: <clusterName> <serviceArn>\s Where: clusterName - The cluster name. serviceArn - The service ARN value. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String clusterName = args[0]; String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() .region(region) .build(); updateSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); } public static void updateSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { UpdateServiceRequest serviceRequest = UpdateServiceRequest.builder() .cluster(clusterName) .service(serviceArn) .desiredCount(0) .build(); ecsClient.updateService(serviceRequest); System.out.println("The service was modified"); } catch (EcsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Para API obter detalhes, consulte UpdateServiceem AWS SDK for Java 2.x APIReferência.