全部产品

查询抢占式实例当前价格

本示例介绍如何使用Alibaba Cloud SDK for Java查询抢占式实例的当前最新价格。

前提条件

在使用本教程之前,请确保已完成以下操作:

  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面查看您的访问密钥。

  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见 阿里云开发工具包(SDK)

    <project>
        <modelVersion>4.0.0</modelVersion>
        <groupId>java.demo</groupId>
        <artifactId>test</artifactId>
        <version>1.0-SNAPSHOT</version>
        <dependencies>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-ecs</artifactId>
                <version>4.19.12</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-core</artifactId>
                <version>4.0.8</version>
            </dependency>
            <dependency>
                <groupId>commons-lang</groupId>
                <artifactId>commons-lang</artifactId>
                <version>2.6</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.68</version>
            </dependency>
        </dependencies>
    </project>

示例代码

本文操作示例主要以代码形式体现,具体代码如下:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.DescribeSpotPriceHistoryRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeSpotPriceHistoryResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeSpotPriceHistoryResponse.SpotPriceType;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 查询最新价格
 */
public class QuerySpotLatestPrice {


    private static IAcsClient client;
    public static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String GMT = "GMT";
    /**请将regionNo修改为您的regionNo*/
    static String regionNo = "cn-beijing";
    /**请将izNo修改为您的zone*/
    static String izNo = "cn-beijing-a";
    /**请将instanceType修改为您的instanceType*/
    static String instanceType = "ecs.g5.8xlarge";
    static String networkType = "vpc";

    public static void main(String[] args) throws ClientException, ParseException {
        client = Initialization();
        describePrice(client);
    }

    /**
     * 查询最新价格
     *
     * @param client
     * @throws ClientException
     * @throws ParseException
     */
    public static void describePrice(IAcsClient client) throws ClientException, ParseException {
        //初始化请求参数
        DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
        request.setInstanceType(instanceType);
        request.setRegionId(regionNo);
        request.setZoneId(izNo);
        request.setStartTime(formatIso8601Date(DateUtils.addDays(Calendar.getInstance().getTime(), -2)));
        request.setNetworkType(networkType);
        System.out.println("地域:" + regionNo + " 实例规格:" + request.getInstanceType() + " 区域:" + request.getZoneId());
        //发送请求
        DescribeSpotPriceHistoryResponse response = client.getAcsResponse(request);
        List<SpotPriceType> priceTypeList = response.getSpotPrices();
        //处理结果,获取最新的价格
        SpotPriceType priceResult = getLatestSpotPriceType(priceTypeList);
        if (null == priceResult) {
            System.out.println("没有查询到结果");
            return;
        }
        System.out.println("抢占式实例价格:" + priceResult.getSpotPrice()+"元");
    }

    /**
     * 获取最新的价格
     *
     * @return
     * @throws ParseException
     */
    private static SpotPriceType getLatestSpotPriceType(List<SpotPriceType> priceTypeList) throws ParseException {
        if (null == priceTypeList || priceTypeList.size() == 0) {
            return null;
        }
        SpotPriceType priceResult = priceTypeList.get(0);
        for (SpotPriceType priceType : priceTypeList) {
            if (parseGMT2LocalDate(priceType.getTimestamp()).getTime() > parseGMT2LocalDate(priceResult.getTimestamp()).getTime()) {
                priceResult = priceType;
            }
        }
        return priceResult;
    }


    /**
     * @param iso8601GmtDate ISO8601格式的gmt时间
     * @throws ParseException
     */
    public static Date parseGMT2LocalDate(String iso8601GmtDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        simpleDateFormat.setTimeZone(SimpleTimeZone.getTimeZone(GMT));
        return simpleDateFormat.parse(iso8601GmtDate);
    }

    /**
     * 将Date类型转换成ISO8601标准表示, 并使用UTC +0时间, 格式为yyyy-MM-ddTHH:mm:ssZ
     *
     * @param date
     * @return
     */
    public static String formatIso8601Date(Date date) {
        SimpleDateFormat rfc822DateFormat = new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US);
        rfc822DateFormat.setTimeZone(new SimpleTimeZone(0, GMT));
        return rfc822DateFormat.format(date);
    }


    /**
     * Initialization  初始化公共请求参数
     */
    private static IAcsClient Initialization() {
        // 初始化请求参数
        DefaultProfile profile = DefaultProfile.getProfile(
                regionNo,                       // 您的地域ID
                "<your-access-key-id>",         // 您的AccessKey ID
                "<your-access-key-secret>");   // 您的AccessKey Secret
        return new DefaultAcsClient(profile);
    }
}

相关链接