教學課程:進階Amazon EC2Spot 請求管理 - AWS SDK for Java 1.x

截至 2024 年 7 月 31 日, AWS SDK for Java 1.x 已進入維護模式,並將end-of-support在 2025 年 12 月 31 日送達。我們建議您遷移至 AWS SDK for Java 2.x,以繼續接收新功能、可用性改善和安全性更新。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

教學課程:進階Amazon EC2Spot 請求管理

Amazon EC2競價型實例允許您對未使用的出價Amazon EC2容量並運行這些實例,只要您的出價超過當前Spot 價格。Amazon EC2根據供應和需求定期更改現貨價格。如需 Spot 執行個體的詳細資訊,請參競價型執行個體中的Amazon EC2Linux 執行個體使用者指南。

先決條件

若要使用本教學課程,您必須具有AWS SDK for Java,並且已滿足其基本的安裝前提條件。請參閱設定AWS SDK for Java以了解詳細資訊。

設置您的憑據

若要開始使用此程式碼範例,您需要設定AWS登入資料。請參閱設定AWS全權證書和區域促進發展如需如何執行此動作的詳細資訊。

注意

建議您使用IAM用户提供這些值。如需詳細資訊,請參閱「」註冊AWS並建立IAM使用者

現在您已配置好自己的設置,可開始使用示例中的代碼。

設定安全羣組

安全組可作為防火牆的角色,可控制允許進出執行個體的流量。默認情況下,啟動實例時沒有任何安全組,這意味着任何 TCP 端口上的所有傳入 IP 流量都將被拒絕。因此,在提交競價請求之前,我們將設置一個允許必要的網絡流量的安全組。在本教程中,我們將創建一個名為「GettingStarted Start」的新安全組,該安全組允許來自運行應用程序的 IP 地址的安全外殼 (SSH) 流量。要設置新的安全組,您需要包含或運行以下以編程方式設置安全組的代碼示例。

在我們創建AmazonEC2客户端對象,我們創建一個CreateSecurityGroupRequest物件的名稱、「GettingStarted」和安全性羣組的描述。然後我們調用ec2.createSecurityGroupAPI 來創建組。

要啟用對該組的訪問,我們創建一個ipPermission對象的 IP 地址範圍設置為本地計算機子網的 CIDR 表示;IP 地址上的「/10」後綴表示指定 IP 地址的子網。我們還配置ipPermission物件與 TCP 協定和端口 22 (SSH) 建立。最後步驟是呼叫ec2 .authorizeSecurityGroupIngress與我們的安全組的名稱和ipPermission物件。

(以下代碼與我們在第一個教程中使用的代碼相同。)

// Create the AmazonEC2Client object so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(credentials) .build(); // Create a new security group. try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest("GettingStartedGroup", "Getting Started Security Group"); ec2.createSecurityGroup(securityGroupRequest); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. System.out.println(ase.getMessage()); } String ipAddr = "0.0.0.0/0"; // Get the IP of the current host, so that we can limit the Security Group // by default to the ip range associated with your subnet. try { // Get IP Address InetAddress addr = InetAddress.getLocalHost(); ipAddr = addr.getHostAddress()+"/10"; } catch (UnknownHostException e) { // Fail here... } // Create a range that you would like to populate. ArrayList<String> ipRanges = new ArrayList<String>(); ipRanges.add(ipAddr); // Open up port 22 for TCP traffic to the associated IP from // above (e.g. ssh traffic). ArrayList<IpPermission> ipPermissions = new ArrayList<IpPermission> (); IpPermission ipPermission = new IpPermission(); ipPermission.setIpProtocol("tcp"); ipPermission.setFromPort(new Integer(22)); ipPermission.setToPort(new Integer(22)); ipPermission.setIpRanges(ipRanges); ipPermissions.add(ipPermission); try { // Authorize the ports to the used. AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest( "GettingStartedGroup",ipPermissions); ec2.authorizeSecurityGroupIngress(ingressRequest); } catch (AmazonServiceException ase) { // Ignore because this likely means the zone has already // been authorized. System.out.println(ase.getMessage()); }

您可以查看整個代碼示例在advanced.CreateSecurityGroupApp.java程式碼範例。請注意,您只需運行此應用程式,即可建立新的安全羣組。

注意

您也可以使用AWS Toolkit for Eclipse。請參閱從管理安全羣組AWS Cost Explorer中的AWS Toolkit for Eclipse用户指南瞭解更多信息。

詳細 Spot 執行個體請求建立選項

正如我們在教學課程:Amazon EC2競價型執行個體此外,您需要使用執行個體類型、Amazon 機器映像 (AMI)、以及最高金額生成請求。

讓我們首先創建一個RequestSpotInstanceRequest物件。請求物件需要您想要的執行個體數量和出價。此外,我們需要設置LaunchSpecification(其中含有執行個體的類型、AMI ID 及想要執行個體使用的安全組)。填充請求後,我們調用requestSpotInstances方法AmazonEC2Client物件。以下是如何請求 Spot 執行個體的範例。

(以下代碼與我們在第一個教程中使用的代碼相同。)

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set up the specifications of the launch. This includes the // instance type (e.g. t1.micro) and the latest Amazon Linux // AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

持久性請求與一次性請求

構建競價請求時,您可以指定多個可選參數。首先是您的請求是僅一次性還是持久性請求。默認情況下,它是一次性請求。一次性請求只能完成一次,在請求的實例終止後,請求將被關閉。只要沒有針對同一請求運行的競價型實例,就會考慮執行持久性請求。要指定請求的類型,您只需要在競價請求上設置類型。這可以透過下列程式碼來完成。

// Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( GettingStartedApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println( "Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set the type of the bid to persistent. requestRequest.setType("persistent"); // Set up the specifications of the launch. This includes the // instance type (e.g. t1.micro) and the latest Amazon Linux // AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

限制請求的持續時間

您還可以選擇指定請求保持有效的時間長度。您可以為此期間指定開始時間和結束時間。默認情況下,競價請求從創建的那一刻起,將考慮執行競價請求,直到您完成或取消該請求。但是,如果需要,您可以限制有效期。下列程式碼中顯示了如何指定期限的範例。

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set the valid start time to be two minutes from now. Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, 2); requestRequest.setValidFrom(cal.getTime()); // Set the valid end time to be two minutes and two hours from now. cal.add(Calendar.HOUR, 2); requestRequest.setValidUntil(cal.getTime()); // Set up the specifications of the launch. This includes // the instance type (e.g. t1.micro) // and the latest Amazon Linux AMI id available. // Note, you should always use the latest Amazon // Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType("t1.micro"); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

分組您的Amazon EC2Spot 執行個體請求

您可以選擇以多種不同的方式對競價型實例請求進行分組。我們將介紹使用啟動組、可用區組和置放羣組的好處。

如果您希望確保您的競價型實例一起啟動和終止,則您可以選擇利用啟動組。啟動組是將一組出價分組在一起的標籤。啟動群組中的所有執行個體會同時啟動和終止。請注意,如果啟動組中的實例已完成,則不能保證使用同一啟動組啟動的新實例也將完成。下列程式碼範例中顯示如何設定啟動羣組的範例。

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 5 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(5)); // Set the launch group. requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP"); // Set up the specifications of the launch. This includes // the instance type (e.g. t1.micro) and the latest Amazon Linux // AMI id available. Note, you should always use the latest // Amazon Linux AMI id or another of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

如果您希望確保請求中的所有實例都在同一個可用區中啟動,並且您不關心哪個實例,則可以利用可用區組。可用區組是一個標籤,它將一組實例分組在同一可用區中。共享一個可用區組並同時履行的所有實例都將在同一可用區中啟動。以下是如何設定可用區域羣組的範例。

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 5 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(5)); // Set the availability zone group. requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP"); // Set up the specifications of the launch. This includes the instance // type (e.g. t1.micro) and the latest Amazon Linux AMI id available. // Note, you should always use the latest Amazon Linux AMI id or another // of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

您可以為 Spot 執行個體指定您想要的可用區。下列程式碼範例示範如何設定可用區。

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set up the specifications of the launch. This includes the instance // type (e.g. t1.micro) and the latest Amazon Linux AMI id available. // Note, you should always use the latest Amazon Linux AMI id or another // of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Set up the availability zone to use. Note we could retrieve the // availability zones using the ec2.describeAvailabilityZones() API. For // this demo we will just use us-east-1a. SpotPlacement placement = new SpotPlacement("us-east-1b"); launchSpecification.setPlacement(placement); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

最後,您可以指定置放羣組如果您使用的是高性能計算 (HPC) 競價型實例,如集羣計算實例或集羣 GPU 實例。置放羣組可在執行個體之間,提供低延遲和高頻寬連線能力。以下是如何設定置放羣組的範例。

// Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set up the specifications of the launch. This includes the instance // type (e.g. t1.micro) and the latest Amazon Linux AMI id available. // Note, you should always use the latest Amazon Linux AMI id or another // of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Set up the placement group to use with whatever name you desire. // For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP". SpotPlacement placement = new SpotPlacement(); placement.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP"); launchSpecification.setPlacement(placement); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

本節中顯示的所有參數均為可選參數。同樣重要的是要認識到,這些參數中的大多數參數(您的出價是一次性出價還是持久性出價除外)都可以降低出價履行的可能性。因此,只有在需要時才利用這些選項是非常重要的。前面的所有代碼示例都被合併為一個長代碼示例,該示例可在com.amazonaws.codesamples.advanced.InlineGettingStartedCodeSampleApp.java類別。

如何在中斷或終止後保留根分區

管理競價型實例中斷的最簡單方法之一是確保您的數據被檢查到 Amazon 彈性塊存儲(AmazonAmazon EBS)在常規節奏上的音量。通過定期檢查點,如果出現中斷,則只會丟失自上次檢查點以來創建的數據(假設兩者之間沒有執行其他非冪等操作)。為了使此過程更加簡單,您可以配置競價請求,以確保您的根分區不會在中斷或終止時被刪除。我們在以下示例中插入了新代碼,説明如何啟用此方案。

在添加的代碼中,我們創建一個BlockDeviceMapping對象並設置其關聯的Amazon Elastic Block Store(Amazon EBS)設置為Amazon EBS對象,我們已配置為not如果競價型實例終止,則刪除。然後我們添加這個BlockDeviceMapping添加到我們在啟動規範中包含的映射的陣列列表。

// Retrieves the credentials from an AWSCredentials.properties file. AWSCredentials credentials = null; try { credentials = new PropertiesCredentials( GettingStartedApp.class.getResourceAsStream("AwsCredentials.properties")); } catch (IOException e1) { System.out.println( "Credentials were not properly entered into AwsCredentials.properties."); System.out.println(e1.getMessage()); System.exit(-1); } // Create the AmazonEC2 client so we can call various APIs. AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); // Initializes a Spot Instance Request RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest(); // Request 1 x t1.micro instance with a bid price of $0.03. requestRequest.setSpotPrice("0.03"); requestRequest.setInstanceCount(Integer.valueOf(1)); // Set up the specifications of the launch. This includes the instance // type (e.g. t1.micro) and the latest Amazon Linux AMI id available. // Note, you should always use the latest Amazon Linux AMI id or another // of your choosing. LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId("ami-a9d09ed1"); launchSpecification.setInstanceType(InstanceType.T1Micro); // Add the security group to the request. ArrayList<String> securityGroups = new ArrayList<String>(); securityGroups.add("GettingStartedGroup"); launchSpecification.setSecurityGroups(securityGroups); // Create the block device mapping to describe the root partition. BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); blockDeviceMapping.setDeviceName("/dev/sda1"); // Set the delete on termination flag to false. EbsBlockDevice ebs = new EbsBlockDevice(); ebs.setDeleteOnTermination(Boolean.FALSE); blockDeviceMapping.setEbs(ebs); // Add the block device mapping to the block list. ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>(); blockList.add(blockDeviceMapping); // Set the block device mapping configuration in the launch specifications. launchSpecification.setBlockDeviceMappings(blockList); // Add the launch specification. requestRequest.setLaunchSpecification(launchSpecification); // Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);

假設您希望在啟動時將此卷重新連接到您的實例,您還可以使用塊儲存設備映射設置。或者,如果您附加了非根分區,則可以指定 AmazonAmazon EBS您希望在競價型實例恢復後連接到競價型實例的卷。您只需通過在EbsBlockDevice和備用設備名稱BlockDeviceMapping物件。通過利用塊儲存設備映射,可以更輕鬆地引導實例。

使用根分區檢查關鍵數據是管理實例中斷可能性的好方法。有關管理中斷可能性的更多方法,請訪問管理中斷影片。

如何標記您的競價請求和實例

新增標籤到Amazon EC2資源可以簡化雲端基礎設施的管理。標籤是一種元數據形式,可用於創建用户友好的名稱,增強可搜索性,並改善多個用户之間的協調。您也可以使用標籤來自動化流程的腳本和部分流程。閲讀有關標記的更多信息Amazon EC2資源,請前往使用標籤中的Amazon EC2Linux 執行個體使用者指南。

標記 請求

要向競價請求添加標籤,您需要標記它們之後他們已經提出要求. 來自的返回值requestSpotInstances()為您提供RequestSpotInstancesResult對象,您可以使用它來獲取用於標記的競價請求 ID:

// Call the RequestSpotInstance API. RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest); List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests(); // A list of request IDs to tag ArrayList<String> spotInstanceRequestIds = new ArrayList<String>(); // Add the request ids to the hashset, so we can determine when they hit the // active state. for (SpotInstanceRequest requestResponse : requestResponses) { System.out.println("Created Spot Request: "+requestResponse.getSpotInstanceRequestId()); spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId()); }

獲得 ID 後,您可以通過將請求的 ID 添加到CreateTagsRequest並呼叫Amazon EC2客户端的createTags()方法:

// The list of tags to create ArrayList<Tag> requestTags = new ArrayList<Tag>(); requestTags.add(new Tag("keyname1","value1")); // Create the tag request CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest(); createTagsRequest_requests.setResources(spotInstanceRequestIds); createTagsRequest_requests.setTags(requestTags); // Tag the spot request try { ec2.createTags(createTagsRequest_requests); } catch (AmazonServiceException e) { System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); }

標記執行個體

與競價請求本身類似,您只能在創建實例後對其進行標記,這將在滿足競價請求後發生(它不再位於開放狀態)。

您可以透過呼叫Amazon EC2客户端的describeSpotInstanceRequests()方法與DescribeSpotInstanceRequestsRequest物件。返回的DescribeSpotInstanceRequestsResult物件包含SpotInstanceRequest對象,可用於查詢 Spot 請求的狀態,並在其執行個體不再位於開放狀態。

競價請求不再打開後,您可以從SpotInstanceRequest對象,通過調用其getInstanceId()方法。

boolean anyOpen; // tracks whether any requests are still open // a list of instances to tag. ArrayList<String> instanceIds = new ArrayList<String>(); do { DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest(); describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds); anyOpen=false; // assume no requests are still open try { // Get the requests to monitor DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest); List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests(); // are any requests open? for (SpotInstanceRequest describeResponse : describeResponses) { if (describeResponse.getState().equals("open")) { anyOpen = true; break; } // get the corresponding instance ID of the spot request instanceIds.add(describeResponse.getInstanceId()); } } catch (AmazonServiceException e) { // Don't break the loop due to an exception (it may be a temporary issue) anyOpen = true; } try { Thread.sleep(60*1000); // sleep 60s. } catch (Exception e) { // Do nothing if the thread woke up early. } } while (anyOpen);

現在,您可以標記返回的實例:

// Create a list of tags to create ArrayList<Tag> instanceTags = new ArrayList<Tag>(); instanceTags.add(new Tag("keyname1","value1")); // Create the tag request CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest(); createTagsRequest_instances.setResources(instanceIds); createTagsRequest_instances.setTags(instanceTags); // Tag the instance try { ec2.createTags(createTagsRequest_instances); } catch (AmazonServiceException e) { // Write out any exceptions that may have occurred. System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); }

取消競價請求和終止實例

取消 Spot 請求

若要取消 Spot 執行個體請求,請呼叫cancelSpotInstanceRequests在Amazon EC2客户端具有CancelSpotInstanceRequestsRequest物件。

try { CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds); ec2.cancelSpotInstanceRequests(cancelRequest); } catch (AmazonServiceException e) { System.out.println("Error cancelling instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); }

終止競價型實例

您可以通過將正在運行的競價型實例的 ID 傳遞給Amazon EC2客户端的terminateInstances()方法。

try { TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateRequest); } catch (AmazonServiceException e) { System.out.println("Error terminating instances"); System.out.println("Caught Exception: " + e.getMessage()); System.out.println("Reponse Status Code: " + e.getStatusCode()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getRequestId()); }

整合練習

為了將這些結合在一起,我們提供了一個更面向對象的方法,將本教程中展示的步驟結合到一個易於使用的類中。我們實例化一個名為Requests來執行這些動作。我們還創建了GettingStartedApp類,它有一個主方法,我們執行高級函數調用。

您可以在以下網址查看或下載本範例的完整源程式碼:GitHub

恭喜您!您已完成高級請求功能教程,該教程用於開發競價型實例軟件AWS SDK for Java。