全部产品

创建与管理无保护期抢占式实例

更新时间:2020-09-25 17:27:33

本示例介绍如何使用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 java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;

import com.alibaba.fastjson.JSON;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
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.ecs.model.v20140526.RunInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.RunInstancesResponse;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang.time.DateUtils;

/**
 * 无保护期抢占式实例代码样例
 */
public class NoDurationSpotSample {

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

    static String regionNo = "cn-beijing";
    static String izNo = "cn-beijing-h";
    static String instanceType = "ecs.g5.8xlarge";

    public static void main(String[] args) {
        IAcsClient client = Initialization();
        describeSpotPriceHistory(client);
        describeSpotCurrentPrice(client);
        createSpotInstance(client);
        describeSpotInstance(client);
    }

    /**
     * <pre>
     *     查看实例是否是无保护期抢占式实例
     *     参照 <a href="https://help.aliyun.com/document_detail/25506.html">OpenAPI DescribeInstances</a>
     * </pre>
     *
     * @param client
     */
    private static void describeSpotInstance(IAcsClient client) {
        try {
            List<String> instanceIds = new ArrayList<String>();
            instanceIds.add("<your-instance-id>");
            DescribeInstancesRequest request = new DescribeInstancesRequest();
            request.setRegionId(regionNo);
            request.setInstanceIds(JSON.toJSONString(instanceIds));
            request.setAcceptFormat(FormatType.JSON);
            DescribeInstancesResponse response = client.getAcsResponse(request);
            if (null != response.getInstances() && response.getInstances().size() > 0) {
                Integer spotDuration = response.getInstances().get(0).getSpotDuration();
                if (spotDuration != null && 0 == spotDuration) {
                    System.out.println("该实例是无保护期类型的抢占式实例");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <pre>
     * 创建无保护期抢占式实例
     * 参照 <a href="https://help.aliyun.com/document_detail/63440.html">OpenAPI RunInstances</a>
     * </pre>
     *
     * @param client
     */
    private static void createSpotInstance(IAcsClient client) {
        try {
            RunInstancesRequest request = new RunInstancesRequest();
            request.setVSwitchId("<your-vsw-id>");
            request.setImageId("<your-image-id>");
            request.setSecurityGroupId("<your-security-group-id>");
            request.setSystemDiskCategory("<your-disk-category>"); // 系统盘类型, 例如 "cloud_ssd"
            request.setSystemDiskSize("<your-disk-size>"); // 系统盘大小, 例如 "40"
            request.setInstanceType(instanceType);
            request.setAmount(1);
            request.setAcceptFormat(FormatType.JSON);
            request.setInstanceChargeType("PostPaid");
            request.setSpotStrategy("SpotAsPriceGo");
            request.putQueryParameter("SpotDuration", 0);
            RunInstancesResponse acsResponse = client.getAcsResponse(request);
            if (null == acsResponse.getInstanceIdSets() || acsResponse.getInstanceIdSets().isEmpty()) {
                return;
            }
            List<String> instanceIdSets = acsResponse.getInstanceIdSets();
            System.out.println("创建成功. 实例ID列表: " + instanceIdSets);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前抢占式实例的收费价格
     *
     * @param client
     */
    private static void describeSpotCurrentPrice(IAcsClient client) {
        try {
            DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
            request.setRegionId(regionNo);
            request.setZoneId(izNo);
            request.setInstanceType(instanceType);
            request.setIoOptimized("optimized");
            request.setNetworkType("vpc");
            String oneDayAgo = formatIso8601Date(DateUtils.addDays(Calendar.getInstance().getTime(), -1));
            request.setStartTime(oneDayAgo);
            //request.putQueryParameter("SpotDuration", 0);
            request.setSpotDuration(0);
            request.setAcceptFormat(FormatType.JSON);
            DescribeSpotPriceHistoryResponse acsResponse = client.getAcsResponse(request);
            if (acsResponse.getSpotPrices() == null || acsResponse.getSpotPrices().isEmpty()) {
                System.out.println("询价失败");
                return;
            }
            // 打印每个时间戳对应的价格信息
            SpotPriceType currentSpotPriceType = acsResponse.getSpotPrices().get(
                acsResponse.getSpotPrices().size() - 1);
            System.out.println("当前抢占式实例价格: " + currentSpotPriceType.getSpotPrice());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <pre>
     * 获取近一天的抢占式实例市场价格
     * 参照 <a href="https://help.aliyun.com/document_detail/60400.html">OpenAPI DescribeSpotPriceHistory</a>
     * </pre>
     *
     * @param client
     */
    private static void describeSpotPriceHistory(IAcsClient client) {
        try {
            DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
            request.setRegionId(regionNo);
            request.setZoneId(izNo);
            request.setInstanceType(instanceType);
            request.setIoOptimized("optimized");
            request.setNetworkType("vpc");
            String oneDayAgo = formatIso8601Date(DateUtils.addDays(Calendar.getInstance().getTime(), -1));
            request.setStartTime(oneDayAgo);
            //request.putQueryParameter("SpotDuration", 0);
            request.setSpotDuration(0);
            request.setAcceptFormat(FormatType.JSON);
            DescribeSpotPriceHistoryResponse acsResponse = client.getAcsResponse(request);
            if (acsResponse.getSpotPrices() == null || acsResponse.getSpotPrices().isEmpty()) {
                return;
            }
            // 打印每个时间戳对应的价格信息
            for (SpotPriceType spotPrice : acsResponse.getSpotPrices()) {
                String iso8601GmtDate = spotPrice.getTimestamp();
                Date date = parseGMT2LocalDate(iso8601GmtDate);
                String dateStr = new SimpleDateFormat(DATE_FORMAT).format(date);
                System.out.println(
                    "日期: " + dateStr + " 原价: " + spotPrice.getOriginPrice() + " 抢占式实例价格: " + spotPrice.getSpotPrice());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

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

相关链接