文档

根据地域、可用区、实例规格、vCPU或内存查询抢占式实例的库存

更新时间:

在新建抢占式实例前,您可以根据实际需要查询抢占式实例库存情况(支持按地域、实例规格或内存大小等维度进行查询),避免因库存不足导致实例创建失败。本文以ECS Java SDK 2.0为例,为您介绍查询某一地域下有库存的抢占式实例规格的方法。

前提条件

  • 已准备阿里云账号以及对应的访问密钥(AccessKey)。

    使用Alibaba Cloud SDK for Java时需要设置阿里云账号的AccessKey信息。AccessKey的获取方式,请参见创建AccessKey

  • 已配置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。具体操作,请参见配置环境变量

  • 已在开发环境中安装ECS Java SDK 2.0。

    您需要在Maven项目中添加以下依赖。具体操作,请参见安装和使用ECS SDK

     <dependencies>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>ecs20140526</artifactId>
            <version>5.1.8</version>
        </dependency>
    
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
    
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency> 
    
    </dependencies>

代码示例

本步骤提供名为QuerySpotAvailableResource的示例类,代码中依次调用了以下接口分别实现功能:

import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

import com.aliyun.ecs20140526.models.DescribeAvailableResourceRequest;
import com.aliyun.ecs20140526.models.DescribeAvailableResourceResponse;
import com.aliyun.ecs20140526.models.DescribeAvailableResourceResponseBody.DescribeAvailableResourceResponseBodyAvailableZonesAvailableZone;
import com.aliyun.ecs20140526.models.DescribeAvailableResourceResponseBody.DescribeAvailableResourceResponseBodyAvailableZonesAvailableZoneAvailableResourcesAvailableResource;
import com.aliyun.ecs20140526.models.DescribeAvailableResourceResponseBody.DescribeAvailableResourceResponseBodyAvailableZonesAvailableZoneAvailableResourcesAvailableResourceSupportedResourcesSupportedResource;
import com.aliyun.ecs20140526.models.DescribeZonesRequest;
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DescribeZonesResponse;
import com.aliyun.ecs20140526.models.DescribeZonesResponseBody.DescribeZonesResponseBodyZones;
import com.aliyun.ecs20140526.models.DescribeZonesResponseBody.DescribeZonesResponseBodyZonesZone;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

public class QuerySpotAvailableResource {

        private static Client client;

        /**请将regionId修改为您想要查询的regionId*/
        private static String regionId = "cn-hangzhou";


        public static void main(String[] args) throws Exception {
            client = createClient();
            /**请将instanceType修改为您想要查询的实例规格*/
            String instanceType = "ecs.n2.3xlarge";
            /**请将cores修改为您想要查询的内核数*/
            Integer cores = 4;
            /**请将memory修改为您想要查询的实例规格的内存大小,单位为GiB*/
            Float memory = 8f;
            //指定地域,查询该地域下所有可用区有库存的抢占式实例规格
            describeRegionAvailableResource();
            //指定规格,查询该地域是否有库存
            describeInstanceTypeAvailableResource(instanceType);
            //指定内核数目内存大小,查询当前地域所有可用区中符合条件的有库存的实例规格
            describeCoresMemoryAvailableResource(cores, memory);
        }


        public static void describeRegionAvailableResource(){
            try {
                Map<String, List<String>> spotAvailableResource= Maps.newHashMap();
                List<String> zones = describeZones();
                zones.stream().forEach(zone->{
                    List<String> instanceTypes = describeAvailableResource(zone, null, 0, 0f);
                    if (CollectionUtils.isNotEmpty(instanceTypes)) {
                        spotAvailableResource.put(zone, instanceTypes);
                    }
                });
                System.out.println(spotAvailableResource);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void describeInstanceTypeAvailableResource(String instanceType){
            List<String> list = Lists.newArrayList();
            try {
                List<String> zones = describeZones();
                zones.stream().forEach(zone->{
                    List<String> instanceTypes = describeAvailableResource(zone, instanceType, 0, 0f);
                    if (CollectionUtils.isNotEmpty(instanceTypes)){
                        list.add(zone);
                    }
                });
                if (CollectionUtils.isNotEmpty(list)){
                    System.out.println("有库存的可用区: " + JSON.toJSONString(list));
                }else {
                    System.out.println("当前地域无库存");
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }


        public static void describeCoresMemoryAvailableResource(Integer cores, Float memory) {
            Map<String, List<String>> spotAvailableResource= Maps.newHashMap();
            try {
                List<String> zones = describeZones();
                zones.stream().forEach(zone -> {
                    List<String> instanceTypes = describeAvailableResource(zone, null, cores, memory);
                    if (CollectionUtils.isNotEmpty(instanceTypes)) {
                        spotAvailableResource.put(zone, instanceTypes);
                    }
                });
                System.out.println(spotAvailableResource);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        public static List<String> describeZones() throws Exception {
            DescribeZonesRequest request = new DescribeZonesRequest();
            request.setRegionId(regionId);
            request.setSpotStrategy("SpotAsPriceGo");
            DescribeZonesResponse response = client.describeZones(request);
            DescribeZonesResponseBodyZones describeZonesResponseBodyZones = response.getBody().getZones();
            List<String> zoneList = Lists.newArrayList();
            if (null != describeZonesResponseBodyZones){
                List<DescribeZonesResponseBodyZonesZone> zones = describeZonesResponseBodyZones.getZone();
                zones.stream().forEach(zone -> {
                    zoneList.add(zone.getZoneId());
                });
            }
            return zoneList;
        }
        public static List<String> describeAvailableResource(String zoneId, String instanceType, Integer cores, Float memory) {
            DescribeAvailableResourceRequest request = new DescribeAvailableResourceRequest();
            request.setRegionId(regionId);
            request.setZoneId(zoneId);
            request.setDestinationResource("InstanceType");
            request.setSpotStrategy("SpotAsPriceGo");
            if (StringUtils.isNotBlank(instanceType)){
                request.setInstanceType(instanceType);
            }
            if (0 != cores){
                request.setCores(cores);
            }
            if (0 != memory){
                request.setMemory(memory);
            }
            List<String> instanceTypes = Lists.newArrayList();
          try {
              DescribeAvailableResourceResponse response = client.describeAvailableResource(request);
              if (null != (response.getBody().getAvailableZones())) {
                  List<DescribeAvailableResourceResponseBodyAvailableZonesAvailableZone> availableZones = response
                      .getBody().getAvailableZones().getAvailableZone();
                  availableZones.stream().forEach(availableZone -> {
                      List<DescribeAvailableResourceResponseBodyAvailableZonesAvailableZoneAvailableResourcesAvailableResource>
                          availableResources = availableZone.getAvailableResources().getAvailableResource();
                      availableResources.stream().forEach(availableResource -> {
                          List<DescribeAvailableResourceResponseBodyAvailableZonesAvailableZoneAvailableResourcesAvailableResourceSupportedResourcesSupportedResource>
                              supportedResources = availableResource.getSupportedResources().getSupportedResource();
                          supportedResources.stream().forEach(supportedResource -> {
                              if ("Available".equals(supportedResource.getStatus()) && "WithStock".equals(
                                  supportedResource.getStatusCategory())) {
                                  instanceTypes.add(supportedResource.getValue());
                              }
                          });
                      });
                  });
          }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instanceTypes;
        }

        private static Client createClient() throws Exception {
            // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                //System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Endpoint 请参考 https://api.aliyun.com/product/Ecs
            config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
            return new Client(config);
        }

}

查询结果的返回示例,如下图所示,表示在杭州地域下符合需求的有库存的实例规格有ecs.c8a.xlarge、ecs.c8i.xlarge等。实例规格返回示例

相关文档