试了下阿里云的OPEN Api

逐渐理解open api的意义,试了下阿里云的续费接口,续费一个月

 package com.test;

 /**
 * @author
 * @date 2018/12/05
 */
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.serializer.SerializerFeature;
 import com.aliyuncs.AcsRequest;
 import com.aliyuncs.AcsResponse;
 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.RenewInstanceRequest;
 import com.aliyuncs.exceptions.ClientException;
 import com.aliyuncs.exceptions.ServerException;
 import com.aliyuncs.profile.DefaultProfile;
 import com.aliyuncs.profile.IClientProfile;

 import java.util.*;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;

 public class  AliyunRenewInstancesExample {

     private String accessKeyId  = "your-accessKeyId";
     private String accessSecret = "your-accessSecret";

     /**
      * 实例所属的地域ID
      */
     private String regionId = "cn-beijing";
     /**
      * 指定的需要续费的实例 ID
      */
     private String[] instanceIds = new String[] {"i-m************"};
     /**
      * 预付费续费时长
      */
     private Integer period = 1;
     /**
      * 续费时长单位,取值:Week/Month
      */
     private String periodUnit = "Month";

     private Map<String, InstanceExpiredModel> instanceExpiredModelMap = new HashMap<String, InstanceExpiredModel>();
     private static final ExecutorService RENEW_INSTANCE_POOL = Executors.newFixedThreadPool(500);
     private static final Integer CHECK_EXPIRED_TIME_OUT_MILLISECOND = 60 * 1000;
     private static final Integer CHECK_EXPIRED_TIME_INTERVAL_MILLISECOND = 2 * 1000;
     private static final String INSTANCE_CHARGE_TYPE_PREPAID = "PrePaid";
     private static final String DESCRIBE_INSTANCES_FILTER_KEY_EXPIRED_START_TIME = "ExpiredStartTime";
     private static final String DESCRIBE_INSTANCES_FILTER_KEY_EXPIRED_END_TIME = "ExpiredEndTime";

     public static void main(String[] args) {
         /**
          * 使用须知:
          * 调用 OpenAPI 续费会自动扣费,请谨慎调用
          * 您的账号必须支持账号余额支付或信用支付,请确保金额充足
          *
          * 调用续费API后会对 新的到期时间 和 原始的到期时间 进行比较并分别输出成功和失败的实例
          */
         new AliyunRenewInstancesExample().callRenewInstance();
     }

     private void callRenewInstance() {
         /**
          * 若需查询需要续费的实例,可查看 describeNeedRenewInstances 方法
          */
         //List<String> needRenewInstanceIds = describeNeedRenewInstances();
         List<String> instanceIdList = Arrays.asList(instanceIds);
         List<DescribeInstancesResponse.Instance> instances = describeInstances(instanceIdList);
         if (!checkInstanceIds(instances, instanceIdList)) {
             return;
         }
         updateInstanceOriginalExpiredTime(instances);
         for (final String instanceId : instanceIdList) {
             RENEW_INSTANCE_POOL.execute(new Runnable() {
                 public void run() {
                     RenewInstanceRequest request = new RenewInstanceRequest();
                     request.setRegionId(regionId);
                     request.setInstanceId(instanceId);
                     request.setPeriod(period);
                     request.setPeriodUnit(periodUnit);
                     callOpenApi(request, instanceExpiredModelMap.get(instanceId));
                 }
             });
         }
         try {
             RENEW_INSTANCE_POOL.shutdown();
             RENEW_INSTANCE_POOL.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         checkInstancesExpiredTime(instanceIdList);
     }
     /**
      * 每2秒中检查一次实例的到期时间,超时时间设为1分钟
      *
      * @param instanceIds 需要检查的实例ID
      */
     private void checkInstancesExpiredTime(List<String> instanceIds) {
         Long startTime = System.currentTimeMillis();
         for (;;) {
             boolean allCompleted = true;
             Long timeStamp = System.currentTimeMillis();
             updateInstanceNewExpiredTime(instanceIds);
             for (String instanceId : instanceExpiredModelMap.keySet()) {
                 InstanceExpiredModel instanceExpiredModel = instanceExpiredModelMap.get(instanceId);
                 if (instanceExpiredModel.newExpiredTime == null && instanceExpiredModel.errorCode == null) {
                     allCompleted = false;
                 }
             }
             if (allCompleted) {
                 logRenewResult();
                 return;
             }
             if (timeStamp - startTime > CHECK_EXPIRED_TIME_OUT_MILLISECOND) {
                 logInfo(String.format("Check instance new expiredTime timeout. Because it takes too much time, View the result detail: %s",
                                 JSON.toJSONString(instanceExpiredModelMap, SerializerFeature.PrettyFormat)));
                 return;
             }
             sleepSomeTime(CHECK_EXPIRED_TIME_INTERVAL_MILLISECOND);
         }
     }

     private boolean checkInstanceIds(List<DescribeInstancesResponse.Instance> instances,
                                      List<String> instanceIds) {
         if (instances.size() != instanceIds.size()) {
             List<String> responseInstanceIds = new ArrayList<String>();
             List<String> invalidInstanceIds = new ArrayList<String>();
             for (DescribeInstancesResponse.Instance instance : instances) {
                 responseInstanceIds.add(instance.getInstanceId());
             }
             for (String instanceId : instanceIds) {
                 if (!responseInstanceIds.contains(instanceId)) {
                     invalidInstanceIds.add(instanceId);
                 }
             }
             logInfo(String.format("Fail. CheckInstanceIds failure. Invalid InstanceIds: %s",
                 JSON.toJSONString(invalidInstanceIds)));
             return false;
         }
         return true;
     }

     /**
      * 记录 instance 原始到期时间,以便在调用续费 OpenAPI 后 check 到期时间是否发生变化来判断续费是否成功
      *
      * @param instances
      * @return
      */
     private boolean updateInstanceOriginalExpiredTime(List<DescribeInstancesResponse.Instance> instances) {
         for (DescribeInstancesResponse.Instance instance : instances) {
             InstanceExpiredModel instanceExpiredModel = new InstanceExpiredModel();
             instanceExpiredModel.instanceId = instance.getInstanceId();
             instanceExpiredModel.originalExpiredTime = instance.getExpiredTime();
             instanceExpiredModelMap.put(instance.getInstanceId(), instanceExpiredModel);
         }
         return true;
     }

     private void updateInstanceNewExpiredTime(List<String> instanceIds) {
         List<DescribeInstancesResponse.Instance> instances = describeInstances(instanceIds);
         for (DescribeInstancesResponse.Instance instance : instances) {
             InstanceExpiredModel instanceExpiredModel = instanceExpiredModelMap.get(instance
                     .getInstanceId());
             if (!instance.getExpiredTime().equals(instanceExpiredModel.originalExpiredTime)) {
                 instanceExpiredModel.newExpiredTime = instance.getExpiredTime();
             }
         }
     }

     private List<DescribeInstancesResponse.Instance> describeInstances(List<String> instanceIds) {
         int offset = 0;
         int pageSize = 100;
         int totalCount = instanceIds.size();
         List<DescribeInstancesResponse.Instance> instances = new ArrayList<DescribeInstancesResponse.Instance>();
         while (offset < totalCount) {
             DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
             describeInstancesRequest.setRegionId(regionId);
             describeInstancesRequest.setPageSize(pageSize);
             describeInstancesRequest.setInstanceChargeType(INSTANCE_CHARGE_TYPE_PREPAID);
             describeInstancesRequest.setInstanceIds(JSON.toJSONString(instanceIds.subList(offset,
                     Math.min(totalCount, offset + pageSize))));
             DescribeInstancesResponse response = callOpenApi(describeInstancesRequest, null);
             if (response == null || response.getInstances().size() == 0) {
                 logInfo(String.format("Fail. Can not find instance. InstanceIds: %s", JSON.toJSONString(instanceIds)));
                 return instances;
             }
             instances.addAll(response.getInstances());
             offset += response.getPageSize();
         }
         return instances;
     }

     private Map<String, InstanceExpiredModel> getFailedInstances() {
         Map<String, InstanceExpiredModel> failedInstances = new HashMap<String, InstanceExpiredModel>();
         for (String instanceId : instanceExpiredModelMap.keySet()) {
             InstanceExpiredModel instanceExpiredModel = instanceExpiredModelMap.get(instanceId);
             if (instanceExpiredModel.errorCode != null) {
                 failedInstances.put(instanceId, instanceExpiredModel);
             }
         }
         return failedInstances;
     }

     private Map<String, InstanceExpiredModel> getSuccessInstances() {
         Map<String, InstanceExpiredModel> successInstances = new HashMap<String, InstanceExpiredModel>();
         for (String instanceId : instanceExpiredModelMap.keySet()) {
             InstanceExpiredModel instanceExpiredModel = instanceExpiredModelMap.get(instanceId);
             if (instanceExpiredModel.errorCode == null
                     && instanceExpiredModel.newExpiredTime != null
                     && !instanceExpiredModel.originalExpiredTime
                             .equals(instanceExpiredModel.newExpiredTime)) {
                 successInstances.put(instanceId, instanceExpiredModel);
             }
         }
         return successInstances;
     }

     /**
      * 调用OpenAPI的方法,这里进行了错误处理
      *
      * @param request AcsRequest, Open API的请求
      * @param <T> AcsResponse 请求所对应返回值
      * @return 返回OpenAPI的调用结果. 如果调用失败,则会返回null
      */
     private <T extends AcsResponse> T callOpenApi(AcsRequest<T> request, BaseResult errorResult) {
         IAcsClient client = initClient();
         try {
             T response = client.getAcsResponse(request, false, 0);
             logInfo(String.format("Success. OpenAPI Action: %s call successfully.",
                     request.getActionName()));
             return response;
         } catch (ClientException e) {
             buildErrResult(errorResult, e);
         }
         return null;
     }

     /**
      * 需要填充账号的AccessKey ID,以及账号的Access Key Secret
      */
     private IAcsClient initClient() {
         IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
         return new DefaultAcsClient(profile);
     }

     private void logRenewResult() {
         logInfo("-------- Renew Instances Result --------");
         Map<String, InstanceExpiredModel> failedInstances = getFailedInstances();
         if (failedInstances.size() > 0) {
             logInfo(String.format("Fail. Some instances renew failure, result: %s",
                 JSON.toJSONString(failedInstances, SerializerFeature.PrettyFormat)));
             Map<String, InstanceExpiredModel> successInstances = getSuccessInstances();
             if (successInstances.size() > 0) {
                 logInfo(String.format("Success. Some instances renew success, result: %s",
                     JSON.toJSONString(successInstances, SerializerFeature.PrettyFormat)));
             }
         } else {
             logInfo(String.format("Success. RenewInstance result: %s", JSON.toJSONString(
                 instanceExpiredModelMap, SerializerFeature.PrettyFormat)));
         }
     }

     private static void sleepSomeTime(int sleepTime) {
         try {
             Thread.sleep(sleepTime);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }

     private static void buildErrResult(BaseResult errResult, ClientException e) {
         if (errResult != null) {
             errResult.errorCode = e.getErrCode();
             errResult.requestId = e.getRequestId();
         }
         if (e instanceof ServerException) {
             logInfo(String.format("Fail. Something with your connection with Aliyun go incorrect. ErrorCode: %s",
                 e.getErrCode()));
         } else {
             logInfo(String.format("Fail. Business error. ErrorCode: %s, RequestId: %s",
                 e.getErrCode(), e.getRequestId()));
         }
     }

     private static void logInfo(String message) {
         System.out.println(message);
     }

     private List<String> describeNeedRenewInstances() {
         String instanceExpiredStartTimeUtc = "2018-10-21T16:00Z";
         String instanceExpiredEndTimeUtc = "2018-12-01T16:00Z";
         List<String> instanceIds = new ArrayList<String>();

         int pageSize = 100;
         int pageNumber = 1;
         int totalCount = 1;
         while (instanceIds.size() < totalCount) {
             DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
             describeInstancesRequest.setRegionId(regionId);
             describeInstancesRequest.setFilter3Key(DESCRIBE_INSTANCES_FILTER_KEY_EXPIRED_START_TIME);
             describeInstancesRequest.setFilter3Value(instanceExpiredStartTimeUtc);
             describeInstancesRequest.setFilter4Key(DESCRIBE_INSTANCES_FILTER_KEY_EXPIRED_END_TIME);
             describeInstancesRequest.setFilter4Value(instanceExpiredEndTimeUtc);
             describeInstancesRequest.setInstanceChargeType(INSTANCE_CHARGE_TYPE_PREPAID);
             describeInstancesRequest.setPageSize(pageSize);
             describeInstancesRequest.setPageNumber(pageNumber);
             DescribeInstancesResponse response = callOpenApi(describeInstancesRequest, null);
             if (response == null || response.getTotalCount() == 0) {
                 logInfo("Fail. DescribeNeedRenewInstances occurred error or response.getTotalCount() == 0");
                 return instanceIds;
             }
             for (DescribeInstancesResponse.Instance instance : response.getInstances()) {
                 instanceIds.add(instance.getInstanceId());
             }
             totalCount = response.getTotalCount();
             pageNumber++;
         }
         logInfo(String.format("Success. DescribeNeedRenewInstances result: %s", instanceIds.toString()));
         return instanceIds;
     }

     class BaseResult {
         public String errorCode;
         public String requestId;
     }

     class InstanceExpiredModel extends BaseResult {
         public String instanceId;
         public String originalExpiredTime;
         public String newExpiredTime;
     }
 }

执行结果,用账户余额支付了一月个的续费

Success. OpenAPI Action: DescribeInstances call successfully.
Success. OpenAPI Action: RenewInstance call successfully.
Success. OpenAPI Action: DescribeInstances call successfully.
-------- Renew Instances Result --------
Success. RenewInstance result: {
    "i-m**********":{
        "instanceId":"i-m************",
        "newExpiredTime":"2019-01-05T16:00Z",
        "originalExpiredTime":"2018-12-05T16:00Z"
    }
}

原文地址:https://www.cnblogs.com/it-worker365/p/10069305.html

时间: 2024-11-08 22:01:50

试了下阿里云的OPEN Api的相关文章

五:用JAVA写一个阿里云VPC Open API调用程序

用JAVA写一个阿里云VPC Open API调用程序 摘要:用JAVA拼出来Open API的URL 引言 VPC提供了丰富的API接口,让网络工程是可以通过API调用的方式管理网络资源.用程序和软件管理自动化管理网络资源是一件显著提升运维效率和网络生产力的事情.产品经理教你写代码系列文章的目标是不懂代码的网络工程师能一步一步的学会用API管理网络. 另外通过文章标题大家也可以看出来,产品经理教你写代码肯定是一个业余班,里面的代码很多写的都不规范,可能也有很多Bug.专业选手可以参考的有限,请

Windows环境下阿里云添加SSH Key及Git配置Key

1. 运行 git-bash.exe 进入命令行 2. 判断是否已存在本地公钥: cat ~/.ssh/id_rsa.pub 如果看到一长串以 ssh-rsa 或 ssh-dsa 开头的字符串,可以跳过 ssh-keygen 步骤 3. 生成 ssh key ssh-keygen -t rsa "自定义标识符" 生成代码会有两个步骤,提示设置密码(默认没有密码).pub文件名称及保持路径,按Enter直接跳过步骤使用默认值.需要注意的是,如果自定义了文件名/路径,需要在 SSH 客户端

nodejs 搞定 阿里云短信API

exports.sendSms=function(phone,content,ret){ var d={ RecNum:phone, Action:'SingleSendSms', SignName:'????', TemplateCode:'?????', ParamString:'{"code":"'+content+'"}', Format:'json', Version:'2016-09-27', SignatureMethod:'HMAC-SHA1', S

基于阿里云 DNS API 实现的 DDNS 工具

0.简要介绍 0.1 思路说明 AliDDNSNet 是基于 .NET Core 开发的动态 DNS 解析工具,借助于阿里云的 DNS API 来实现域名与动态 IP 的绑定功能.工具核心就是调用了阿里云 DNS 的两个 API ,一个 API 获取指定域名的所有解析记录,然后通过比对与当前公网 IP 是否一致,一致则不进行更改,不一致则通过另外一个修改 API 来修改指定子域名的修改记录. 0.2 使用说明 使用时请更改同目录下的 settings.json.example 为 setting

从量子加密到机器学习,盘点2015阿里云开放的黑科技

http://www.csdn.net/article/2015-12-18/2826512 摘要:因为云计算应用的不断深入.以及对大数据处理需求的不断扩大,用户要求功能丰富.性能强大.高可用性的产品,云计算厂商们也推陈出新,不断地推出新产品,本文就盘点了业内翘楚阿里云在2015年那些有价值的新产品. 作为云计算产业热土的中国.2015年产业规模依然保持快速增长.且国内的公有云服务领域有几十家企业在角逐.经过几年的发展,眼下市场逐渐明朗.有些公有云企业已经遥遥率先,而有些企业非常可惜,已经開始掉

阿里云学习方法及目标

先吐槽下自己: 第一次用云服务器,感觉自己弱爆了... 各种专业术语看着就头大,什么ECS.OSS.实例.Bucket,地域,I/O... 还是用虚拟主机方便啊...PHP或ASP主机,下载个源码,FTP它,解析绑定域名,一路NEXT安装,OK,网站上线了... 现在看来,自己原来只懂得这么肤浅的内容啊... 再也不好意思向人说自己会做网站了... 再吐槽下阿里云: 第一次试图使用阿里云的云服务器在购买环节就碰壁了,什么是实例规格族?I/O优化?SSD云盘和高效云盘还有普通云盘怎么选择?这里的C

阿里云OSS

想将图片存储到阿里云上,尝试着了解了下阿里云的OSS. 文档地址:https://help.aliyun.com/?spm=5176.doc31837.201511181.1.TePvVX .net 版本SDK 的github地址:https://github.com/aliyun/aliyun-oss-csharp-sdk?spm=5176.doc32085.2.4.kSjabk 贴个OSS开通的region 和endpoint 的图,地址:https://help.aliyun.com/do

用七年时间造出的阿里云,如今三句话告诉你是什么

马云在2016年10月杭州云栖大会的主题演讲中只字未提"阿里云",但这并不说明阿里云不重要,而是在某种意义上说明在马云的心里,阿里云"从0到1"的阶段已经完成了. 在10月13日杭州云栖大会开幕当天,马云发表了就上一财年致股东信,信中提及阿里云承载了中国35%的网站并为之提供云计算和大数据的服务,而截至2016年3月31日的阿里财报显示阿里云拥有超过230万用户,其中云计算付费用户达50万. 从2009年2月写下阿里云的第一段代码开始,阿里云上上下下的负责人们就一直

你好 阿里云

时间过得真快,备案快要通过下来了,自己也马上要成为一个真正的站长了,今天就来说一下我如何使用"云平台方案调研/技术选型"."云上建站/开发过程"."架构解析/优化"."上云前后对比"."遇到的问题及解决方案"经历吧. '为了无法计算的价值',每每想起心里还是很汹涌澎湃的,这就是牛,一句话过了很久也会让人打了鸡血般的激动,这也是我喜欢阿里云的原因之一. 云平台方案调研/技术选型 言归正传,阿里算是做云服务最早