全部產品
Search
文件中心

:Java SDK使用樣本

更新時間:Jun 19, 2024

本文為您介紹Resource Orchestration Service服務ROS(Resource Orchestration Service)的Java SDK安裝方法和範例程式碼。以查詢可用地區列表、建立資源棧、查詢資源棧、刪除資源棧等操作為例,協助您快速掌握Resource Orchestration Service介面的使用方法。

安裝Java SDK

  1. 下載及安裝Java SDK。

    說明
    • Java SDK的下載和使用說明,請參見SDK概覽

    • 建議您使用JRE 1.8及以上版本。

  2. pom.xml中,添加依賴包。

    <dependencies>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>ros20190910</artifactId>
          <version>2.2.20</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-openapi</artifactId>
          <version>0.2.8</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-console</artifactId>
          <version>0.0.1</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea-util</artifactId>
          <version>0.2.16</version>
        </dependency>
        <dependency>
          <groupId>com.aliyun</groupId>
          <artifactId>tea</artifactId>
          <version>1.1.14</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>darabonba-env</artifactId>
            <version>0.1.1</version>
         </dependency>
      	<dependency>
        		<groupId>com.aliyun</groupId>
        		<artifactId>credentials-java</artifactId>
        		<version>0.2.11</version>
    		</dependency>
      </dependencies>
  3. 初始化SDK。

    1. 匯入相關的軟體包。

      import com.aliyun.tea.*;
      import com.aliyun.ros20190910.*;
      import com.aliyun.ros20190910.models.*;
      import com.aliyun.teaopenapi.*;
      import com.aliyun.teaopenapi.models.*;
      import com.aliyun.darabonba.env.*;
      import com.aliyun.credentials.*;
      import java.util.*;
    2. 初始化SDK用戶端對象。

      public static com.aliyun.ros20190910.Client createClient() throws Exception {
              // 使用預設憑證初始化Credentials Client
              com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
              Config config = new Config()
                      // 配置雲產品服務接入地址(endpoint)
                      .setEndpoint("ros.aliyuncs.com")
                      // 使用Credential配置憑證
                      .setCredential(credentialClient);
              return new com.aliyun.ros20190910.Client(config);
          }

樣本

  • 查詢可用地區列表示例

    通過調用DescribeRegions介面查詢可用地區列表。關於DescribeRegions介面的詳情,請參見DescribeRegions

    public static void describeRegions(Client client) throws Exception {
            DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();
            // 複製代碼運行後,請自行列印API的傳回值。
            DescribeRegionsResponse resp = client.describeRegions(describeRegionsRequest);
        }
  • 建立資源棧樣本

    通過調用CreateStack介面建立資源棧。關於CreateStack介面的詳情,請參見CreateStack

    在本樣本中,指定了以下參數:

    • regionId:資源棧所屬的地區ID。

    • stackName:資源棧名稱。同一阿里雲帳號中資源棧名稱不能重複。

    • timeoutInMinutes:建立資源棧的逾時時間,單位為分鐘。如果在指定時間內不能完成建立,則資源棧建立失敗。

    • templateBody:模板的主體結構。

    • parameters:建立的資源棧所需要的參數。需要同時指定ParameterKey和ParameterValue。

    參數設定的執行個體代碼如下所示。

    String stackName = "MyStack";
    Long timeoutInMinutes = 40L;
    String templateBody = "{\n" +
                          "  \"ROSTemplateFormatVersion\": \"2015-09-01\",\n" +
                          "  \"Parameters\": {\n" +
                          "    \"VpcName\": {\n" +
                          "      \"Type\": \"String\",\n" +
                          "      \"Description\": \"Vpc Name\",\n" +
                          "      \"Label\": \"Vpc Name\"\n" +
                          "    },\n" +
                          "    \"CidrBlock\": {\n" +
                          "      \"Type\": \"String\",\n" +
                          "      \"Description\": \"Vpc CidrBlock\",\n" +
                          "      \"Label\": \"Vpc CidrBlock\"\n" +
                          "    }\n" +
                          "  },\n" +
                          "  \"Resources\": {\n" +
                          "    \"Vpc\": {\n" +
                          "      \"Type\": \"ALIYUN::ECS::VPC\",\n" +
                          "      \"Properties\": {\n" +
                          "        \"CidrBlock\": {\n" +
                          "          \"Ref\": \"CidrBlock\"\n" +
                          "        },\n" +
                          "        \"VpcName\": {\n" +
                          "          \"Ref\": \"VpcName\"\n" +
                          "        }\n" +
                          "      }\n" +
                          "    }\n" +
                          "  }\n" +
                          "}";
    CreateStackRequest.CreateStackRequestParameters parameters0 = new CreateStackRequest.CreateStackRequestParameters()
                    .setParameterKey("VpcName")
                    .setParameterValue("TestVpc");
    CreateStackRequest.CreateStackRequestParameters parameters1 = new CreateStackRequest.CreateStackRequestParameters()
                    .setParameterKey("CidrBlock")
                    .setParameterValue("192.168.0.0/16");
    
    List parameters = java.util.Arrays.asList(parameters0, parameters1);

    參數設定的範例程式碼如下所示。

    public static void createStack(Client client, String regionId, String stackName, String templateBody, Long timeoutInMinutes, List parameters) throws Exception {
        CreateStackRequest createStackRequest = new CreateStackRequest()
                .setTemplateBody(templateBody)
                .setStackName(stackName)
                .setRegionId(regionId)
                .setTimeoutInMinutes(timeoutInMinutes)
                .setParameters(parameters);
         // 複製代碼運行後,請自行列印API的傳回值。
         CreateStackResponse resp = client.createStack(createStackRequest);
         com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
    }
  • 查詢資源棧樣本

    通過調用GetStack介面查詢資源棧資訊。關於GetStack介面的詳情,請參見GetStack

    在本樣本中,指定了以下參數:

    • stackId:資源棧ID。

    • regionId:資源棧所屬的地區ID。

    參數設定的範例程式碼如下:

public static void getStack(Client client, String stackId, String regionId) throws Exception {        
    GetStackRequest getStackRequest = new GetStackRequest()            
        .setStackId(stackId)            
        .setRegionId(regionId);    
        // 複製代碼運行後,請自行列印API的傳回值。    
    GetStackResponse resp = client.getStack(getStackRequest);    
    com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
}
  • 刪除資源棧樣本

    通過調用DeleteStack介面刪除資源棧。關於DeleteStack介面的詳情,請參見DeleteStack

    在本樣本中,指定了以下參數:

    • regionId:資源棧所屬的地區ID。

    • stackId:資源棧ID。

  • 參數設定的範例程式碼如下所示。

public static void deleteStack(Client client, String stackId, String regionId) throws Exception {    
    DeleteStackRequest deleteStackRequest = new DeleteStackRequest()
                .setStackId(stackId)
                .setRegionId(regionId);
    // 複製代碼運行後,請自行列印API的傳回值。
    DeleteStackResponse resp = client.deleteStack(deleteStackRequest);
    com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
}
  • 完整樣本

    以下為查詢可用地區列表、建立資源棧、查詢資源棧和刪除資源棧的完整操作樣本。

    說明

    調用介面前,需配置環境變數,通過環境變數讀取存取憑證。更多資訊,請參見配置訪問憑證

    AccessKey ID和AccessKey Secret的環境變數名:ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET

    package com.aliyun.sample;
    
    import com.aliyun.ros20190910.Client;
    import com.aliyun.tea.*;
    import com.aliyun.ros20190910.*;
    import com.aliyun.ros20190910.models.*;
    import com.aliyun.teaopenapi.*;
    import com.aliyun.teaopenapi.models.*;
    import com.aliyun.darabonba.env.*;
    import java.util.*;
    
    
    
    public class Sample {
    
        /**
         * 初始化帳號Client
         * @return Client
         * @throws Exception
         */
        private static String REGIONID = "Region Id";
    
        public static com.aliyun.ros20190910.Client createClient() throws Exception {
            // 使用預設憑證初始化Credentials Client。
            com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
            Config config = new Config()
                    // 配置雲產品服務接入地址(endpoint)
                    .setEndpoint("ros.aliyuncs.com")
                    // 使用Credential配置憑證
                    .setCredential(credentialClient);
            return new com.aliyun.ros20190910.Client(config);
        }
    
        public static void describeRegions(Client client) throws Exception {
            DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();
            // 複製代碼運行後,請自行列印API的傳回值。
            DescribeRegionsResponse resp = client.describeRegions(describeRegionsRequest);
        }
    
        public static void getStack(Client client, String stackId, String regionId,  Boolean wait) throws Exception {
            GetStackRequest getStackRequest = new GetStackRequest()
                    .setStackId(stackId)
                    .setRegionId(regionId);
            // 複製代碼運行後,請自行列印API的傳回值。
            GetStackResponse response = client.getStack(getStackRequest);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
            GetStackResponseBody body = response.body;
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
            if (wait) {
                if (com.aliyun.teautil.Common.equalString(body.status, "CREATE_IN_PROGRESS")) {
                    com.aliyun.teaconsole.Client.log("正在建立中......");
                    com.aliyun.teautil.Common.sleep(30000);
                    Sample.getStack(client, stackId, regionId, wait);
                } else if (com.aliyun.teautil.Common.equalString(body.status, "CREATE_FAILED")) {
                    com.aliyun.teaconsole.Client.log("建立失敗, 資訊:" + body.statusReason + ", requestId:" + body.requestId + "");
                } else if (com.aliyun.teautil.Common.equalString(body.status, "CREATE_COMPLETE")) {
                    com.aliyun.teaconsole.Client.log("建立成功");
                    com.aliyun.teaconsole.Client.log("ID:" + body.stackId + "");
                }
    
            } else {
                com.aliyun.teaconsole.Client.log("ID:" + body.stackId + "");
                com.aliyun.teaconsole.Client.log("狀態:" + body.status + "");
            }
        }
    
    
        public static void deleteStack(Client client, String stackId, String regionId) throws Exception {
            DeleteStackRequest deleteStackRequest = new DeleteStackRequest()
                    .setStackId(stackId)
                    .setRegionId(regionId);
            // 複製代碼運行後,請自行列印API的傳回值。
            DeleteStackResponse resp = client.deleteStack(deleteStackRequest);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
        }
    
        public static String createStack(Client client, String regionId, String stackName, String templateBody, Long timeoutInMinutes, java.util.List parameters) throws Exception {
            CreateStackRequest createStackRequest = new CreateStackRequest()
                .setTemplateBody(templateBody)
                .setStackName(stackName)
                .setRegionId(regionId)
                .setTimeoutInMinutes(timeoutInMinutes)
                .setParameters(parameters);
            // 複製代碼運行後,請自行列印API的傳回值。
            CreateStackResponse resp = client.createStack(createStackRequest);
            com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
            return resp.body.stackId;
        }
    
        public static void main(String[] args_) throws Exception {
            String stackName = "MyStack";
            String parameter =" {\"ParameterKey\": \"VpcName\", \"ParameterValue\": \"test_vpc\"}";
            Long timeoutInMinutes = 40L;
            String templateBody = "{\n" +
                            "  \"ROSTemplateFormatVersion\": \"2015-09-01\",\n" +
                            "  \"Parameters\": {\n" +
                            "    \"VpcName\": {\n" +
                            "      \"Type\": \"String\",\n" +
                            "      \"Description\": \"Vpc Name\",\n" +
                            "      \"Label\": \"Vpc Name\"\n" +
                            "    },\n" +
                            "    \"CidrBlock\": {\n" +
                            "      \"Type\": \"String\",\n" +
                            "      \"Description\": \"Vpc CidrBlock\",\n" +
                            "      \"Label\": \"Vpc CidrBlock\"\n" +
                            "    }\n" +
                            "  },\n" +
                            "  \"Resources\": {\n" +
                            "    \"Vpc\": {\n" +
                            "      \"Type\": \"ALIYUN::ECS::VPC\",\n" +
                            "      \"Properties\": {\n" +
                            "        \"CidrBlock\": {\n" +
                            "          \"Ref\": \"CidrBlock\"\n" +
                            "        },\n" +
                            "        \"VpcName\": {\n" +
                            "          \"Ref\": \"VpcName\"\n" +
                            "        }\n" +
                            "      }\n" +
                            "    }\n" +
                            "  }\n" +
                            "}";
            com.aliyun.ros20190910.Client client = Sample.createClient();
    
            Sample.describeRegions(client);
            CreateStackRequest.CreateStackRequestParameters parameters0 = new CreateStackRequest.CreateStackRequestParameters()
                    .setParameterKey("VpcName")
                    .setParameterValue("TestVpc");
            CreateStackRequest.CreateStackRequestParameters parameters1 = new CreateStackRequest.CreateStackRequestParameters()
                    .setParameterKey("CidrBlock")
                    .setParameterValue("192.168.0.0/16");
    
            List parameters = java.util.Arrays.asList(parameters0, parameters1);
            String stackId = Sample.createStack(client, REGIONID, stackName, templateBody, timeoutInMinutes, parameters);
            Sample.getStack(client, stackId, REGIONID, true);
            Sample.deleteStack(client, stackId, REGIONID);
        }
    }