Tutorial: LanjutanAmazon EC2Manajemen permintaan spot - AWS SDK for Java 1.x

AWS SDK for Java 1.x telah memasuki mode pemeliharaan pada 31 Juli 2024, dan akan mencapai end-of-supportpada 31 Desember 2025. Kami menyarankan Anda bermigrasi ke AWS SDK for Java 2.xuntuk terus menerima fitur baru, peningkatan ketersediaan, dan pembaruan keamanan.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Tutorial: LanjutanAmazon EC2Manajemen permintaan spot

Amazon EC2Instans Spot memungkinkan Anda untuk menawar pada yang tidak digunakanAmazon EC2kapasitas dan menjalankan instans tersebut selama tawaran Anda melebihi saat iniharga spot.Amazon EC2mengubah harga spot secara berkala berdasarkan penawaran dan permintaan. Untuk informasi selengkapnya tentang Instans Spot Instans, lihatSpot Instancedi dalamAmazon EC2Panduan Pengguna untuk Instans Linux.

Prasyarat

Untuk menggunakan tutorial ini Anda harus memilikiAWS SDK for Javadiinstal, serta telah memenuhi prasyarat instalasi dasar. LihatMenyiapkanAWS SDK for JavaUntuk informasi lebih lanjut.

Menyiapkan kredenensi Anda

Untuk mulai menggunakan sampel kode ini, Anda perlu mengaturAWSkredensi. LihatMengaturAWSKredensi dan Wilayah untuk Pembangunanuntuk petunjuk tentang cara melakukannya.

catatan

Sebaiknya Anda menggunakan kredenensiIAMpengguna untuk memberikan nilai-nilai ini. Untuk informasi selengkapnya, lihatMendaftarAWSdan BuatIAMPengguna.

Setelah Anda mengkonfigurasi pengaturan Anda, Anda dapat memulai menggunakan kode dalam contoh.

Menyiapkan grup keamanan

Grup keamanan bertindak sebagai firewall yang mengontrol lalu lintas yang diizinkan masuk dan keluar dari grup instans. Secara default, sebuah instance dimulai tanpa grup keamanan apa pun, yang berarti bahwa semua lalu lintas IP yang masuk, pada port TCP mana pun akan ditolak. Jadi, sebelum mengirimkan Permintaan Spot kami, kami akan menyiapkan grup keamanan yang memungkinkan lalu lintas jaringan yang diperlukan. Untuk tujuan tutorial ini, kita akan membuat grup keamanan baru yang disebut “GettingStarted” yang memungkinkan lalu lintas Secure Shell (SSH) dari alamat IP tempat Anda menjalankan aplikasi Anda. Untuk menyiapkan grup keamanan baru, Anda harus menyertakan atau menjalankan contoh kode berikut yang mengatur grup keamanan secara terprogram.

Setelah kita membuatAmazonEC2objek klien, kita membuatCreateSecurityGroupRequestobjek dengan nama, “gettingStarted” dan deskripsi untuk grup keamanan. Lalu kita sebutec2.createSecurityGroupAPI untuk membuat grup.

Untuk mengaktifkan akses ke grup, kita membuatipPermissionobjek dengan rentang alamat IP diatur ke representasi CIDR dari subnet untuk komputer lokal; akhiran “/10" pada alamat IP menunjukkan subnet untuk alamat IP yang ditentukan. Kami juga mengkonfigurasiipPermissionobjek dengan protokol TCP dan port 22 (SSH). Langkah terakhir adalah memanggilec2 .authorizeSecurityGroupIngressdengan nama grup keamanan kami danipPermissionobjek.

(Kode berikut adalah sama dengan apa yang kita gunakan dalam tutorial pertama.)

// 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()); }

Anda dapat melihat seluruh contoh kode ini diadvanced.CreateSecurityGroupApp.javasampel kode. Perhatikan bahwa Anda hanya perlu menjalankan aplikasi ini sekali untuk membuat grup keamanan baru.

catatan

Anda juga dapat membuat grup keamanan menggunakanAWS Toolkit for Eclipse. LihatMengelola Grup Keamanan dariAWS Cost Explorerdi dalamAWS Toolkit for EclipsePanduan Pengguna untuk informasi lebih lanjut.

Opsi pembuatan permintaan Instans Spot Instance

Seperti yang kita jelaskan diTutorial:Amazon EC2 Spot Instance, Anda perlu membuat permintaan Anda dengan tipe instans, Amazon Machine Image (AMI), dan harga bid maksimum.

Mari kita mulai dengan membuatRequestSpotInstanceRequestobjek. Objek permintaan memerlukan jumlah instans yang Anda inginkan dan harga penawaran. Selain itu, kita perlu mengaturLaunchSpecificationuntuk permintaan, yang mencakup jenis instans, ID AMI, dan grup keamanan yang ingin Anda gunakan. Setelah permintaan diisi, kami memanggilrequestSpotInstancesmetode pada metodeAmazonEC2Clientobjek. Contoh cara meminta Instans Spot berikut.

(Kode berikut adalah sama dengan apa yang kita gunakan dalam tutorial pertama.)

// 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);

Permintaan persisten vs satu kali

Saat membuat permintaan Spot, Anda dapat menentukan beberapa parameter opsional. Yang pertama adalah apakah permintaan Anda hanya satu kali atau persisten. Secara default, ini adalah permintaan satu kali. Permintaan satu kali hanya dapat dipenuhi sekali, dan setelah instans yang diminta dihentikan, permintaan akan ditutup. Permintaan persisten dipertimbangkan untuk pemenuhan setiap kali tidak ada Instans Spot yang berjalan untuk permintaan yang sama. Untuk menentukan jenis permintaan, Anda hanya perlu mengatur Type pada permintaan Spot. Hal ini dapat dilakukan dengan kode berikut.

// 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);

Membatasi durasi permintaan

Anda juga dapat menentukan jangka waktu permintaan Anda akan tetap valid. Anda dapat menentukan waktu mulai dan akhir untuk periode ini. Secara default, permintaan Spot akan dipertimbangkan untuk pemenuhan dari saat dibuat sampai permintaan tersebut terpenuhi atau dibatalkan oleh Anda. Namun Anda dapat membatasi masa berlaku jika Anda perlu. Contoh cara menentukan periode ini ditampilkan dalam kode berikut.

// 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);

MengelompokkanAmazon EC2Permintaan Instans Spot

Anda memiliki opsi untuk mengelompokkan permintaan Instans Spot Anda dengan beberapa cara yang berbeda. Kita akan melihat manfaat menggunakan grup peluncuran, grup Availability Zone, dan grup penempatan.

Jika Anda ingin memastikan Instans Spot Anda semua diluncurkan dan dihentikan bersama, maka Anda memiliki opsi untuk memanfaatkan grup peluncuran. Sebuah grup peluncuran adalah label yang mengelompokkan satu set tawaran bersama-sama. Semua instance dalam grup peluncuran dimulai dan diakhiri bersama. Catatan, jika instance dalam grup peluncuran telah terpenuhi, tidak ada jaminan bahwa instans baru yang diluncurkan dengan grup peluncuran yang sama juga akan terpenuhi. Contoh cara mengatur Grup Peluncuran ditampilkan dalam contoh kode berikut.

// 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);

Jika Anda ingin memastikan bahwa semua instans dalam permintaan diluncurkan di Availability Zone yang sama, dan Anda tidak peduli yang mana, Anda dapat memanfaatkan grup Availability Zone. Grup Availability Zone adalah label yang mengelompokkan satu set instance bersama-sama di Availability Zone yang sama. Semua instance yang berbagi grup Availability Zone dan terpenuhi pada saat yang sama akan dimulai di Availability Zone yang sama. Contoh cara mengatur grup Availability Zone berikut.

// 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);

Anda dapat menentukan Availability Zone yang Anda inginkan untuk Instans Spot. Contoh kode berikut menunjukkan cara mengatur Availability Zone.

// 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);

Terakhir, Anda dapat menentukangrup penempatanjika Anda menggunakan Instans Spot Komputasi Kinerja Tinggi (HPC), seperti instans komputasi klaster atau instans GPU klaster. Grup penempatan memberi Anda latensi yang lebih rendah dan konektivitas bandwidth tinggi antara instans. Contoh cara mengatur grup penempatan berikut.

// 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);

Semua parameter yang ditunjukkan dalam bagian ini adalah opsional. Penting juga untuk menyadari bahwa sebagian besar parameter ini—dengan pengecualian apakah tawaran Anda satu kali atau persisten—dapat mengurangi kemungkinan pemenuhan tawaran. Jadi, penting untuk memanfaatkan opsi ini hanya jika Anda membutuhkannya. Semua contoh kode sebelumnya digabungkan menjadi satu contoh kode panjang, yang dapat ditemukan dicom.amazonaws.codesamples.advanced.InlineGettingStartedCodeSampleApp.javakelas.

Cara bertahan partisi root setelah gangguan atau penghentian

Salah satu cara termudah untuk mengelola gangguan Instans Spot Anda adalah memastikan bahwa data Anda diperiksa ke Amazon Elastic Block Store (AmazonAmazon EBS) volume pada irama biasa. Dengan checkpointing secara berkala, jika ada gangguan Anda akan kehilangan hanya data yang dibuat sejak pos pemeriksaan terakhir (dengan asumsi tidak ada tindakan non-idempoten lainnya yang dilakukan di antaranya). Agar proses ini lebih mudah, Anda dapat mengonfigurasi Permintaan Spot untuk memastikan bahwa partisi root Anda tidak akan dihapus saat gangguan atau penghentian. Kami telah memasukkan kode baru dalam contoh berikut yang menunjukkan bagaimana mengaktifkan skenario ini.

Dalam kode tambahan, kita membuatBlockDeviceMappingobjek dan mengatur terkaitAmazon Elastic Block Store(Amazon EBS) ke sebuahAmazon EBSobjek yang telah kita konfigurasi untuknotdihapus jika Instans Spot dihentikan. Kami kemudian menambahkan iniBlockDeviceMappingke ArrayList pemetaan yang kami sertakan dalam spesifikasi peluncuran.

// 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);

Dengan asumsi Anda ingin melampirkan kembali volume ini ke instans Anda saat startup, Anda juga dapat menggunakan pengaturan pemetaan perangkat blok. Atau, jika Anda memasang partisi non-root, Anda dapat menentukan AmazonAmazon EBSvolume yang ingin Anda lampirkan ke Instans Spot setelah dilanjutkan. Anda melakukan ini hanya dengan menentukan ID snapshot di AndaEbsBlockDevicedan nama perangkat alternatif diBlockDeviceMappingobjek. Dengan memanfaatkan pemetaan perangkat blok, dapat lebih mudah untuk bootstrap contoh Anda.

Menggunakan partisi root untuk memeriksa data kritis Anda adalah cara yang bagus untuk mengelola potensi gangguan instans Anda. Untuk metode lebih lanjut tentang mengelola potensi gangguan, silakan kunjungiMengelola Interupsivideo.

Cara menandai permintaan dan instans spot Anda

Menambahkan tanda keAmazon EC2sumber daya dapat menyederhanakan administrasi infrastruktur cloud Anda. Sebuah bentuk metadata, tag dapat digunakan untuk membuat nama yang user-friendly, meningkatkan penelusuran, dan meningkatkan koordinasi antara beberapa pengguna. Anda juga dapat menggunakan tanda untuk mengotomatisasi skrip dan bagian proses Anda. Untuk membaca lebih lanjut tentang penandaanAmazon EC2sumber daya, pergi keMenggunakan Tagdi dalamAmazon EC2Panduan Pengguna untuk Instans Linux.

Permintaan penandaan

Untuk menambahkan tag ke permintaan tempat Anda, Anda perlu memberi tag pada merekasetelahmereka telah diminta. Nilai kembali darirequestSpotInstances()menyediakan Anda denganRequestSpotInstancesResultobjek yang dapat Anda gunakan untuk mendapatkan ID permintaan spot untuk penandaan:

// 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()); }

Setelah Anda memiliki ID, Anda dapat menandai permintaan dengan menambahkan ID mereka keCreateTagsRequestdan memanggilAmazon EC2kliencreateTags()Metode:

// 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()); }

Menandai instans

Demikian pula untuk melihat permintaan sendiri, Anda hanya dapat menandai sebuah instance setelah dibuat, yang akan terjadi setelah permintaan spot telah terpenuhi (itu tidak lagi diterbukanegara).

Anda dapat memeriksa status permintaan Anda dengan menghubungiAmazon EC2kliendescribeSpotInstanceRequests()metode denganDescribeSpotInstanceRequestsRequestobjek. KembalianDescribeSpotInstanceRequestsResultobjek berisi daftarSpotInstanceRequestobjek yang dapat Anda gunakan untuk query status permintaan spot Anda dan mendapatkan ID instans mereka setelah mereka tidak lagi diterbukanegara.

Setelah permintaan spot tidak lagi terbuka, Anda dapat mengambil ID instans dariSpotInstanceRequestobjek dengan memanggil nyagetInstanceId()metode.

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);

Sekarang Anda dapat menandai contoh yang dikembalikan:

// 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()); }

Membatalkan permintaan spot dan mengakhiri instans

Membatalkan permintaan spot

Untuk membatalkan permintaan Instans Spot Instans Spot InstanscancelSpotInstanceRequestspadaAmazon EC2klien denganCancelSpotInstanceRequestsRequestobjek.

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()); }

Mengakhiri Instans Spot

Anda dapat mengakhiri Instans Spot apa pun yang berjalan dengan meneruskan ID mereka keAmazon EC2klienterminateInstances()metode.

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()); }

Membawa semuanya bersama-sama

Untuk menyatukan semua ini, kami menyediakan pendekatan yang lebih berorientasi objek yang menggabungkan langkah-langkah yang kami tunjukkan dalam tutorial ini menjadi satu kelas yang mudah digunakan. Kami instantiate kelas disebutRequestsyang melakukan tindakan ini. Kami juga membuatGettingStartedAppkelas, yang memiliki metode utama di mana kita melakukan panggilan fungsi tingkat tinggi.

Kode sumber lengkap untuk contoh ini dapat dilihat atau diunduh diGitHub.

Selamat! Anda telah menyelesaikan tutorial Fitur Permintaan Lanjutan untuk mengembangkan perangkat lunak Instans Spot denganAWS SDK for Java.