阿里雲資源編排服務JavaSDK使用入門

ros-test發表於2017-06-29

阿里雲資源編排服務 Java SDK使用入門

安裝依賴

新增Maven庫

<repositories>
    <repository>
        <id>sonatype-nexus-staging</id>
        <name>Sonatype Nexus Staging</name>
        <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

在專案中包含依賴

建立一個新的maven專案,或者在您已有的專案中通過maven引入依賴:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>3.2.4</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-ros</artifactId>
    <version>2.2.6</version>
</dependency>

ROS JAVA SDK 與伺服器通過 HTTP 的方式互動,HTTP Request 和 Response 的內容為 json 格式的字串,請在程式碼中引入合適的 json 包,如:

import org.json.JSONObject;

示例中使用的版本為:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20170516</version>
</dependency>

初始化客戶端

在您準備呼叫SDKjava類中引入相關的包:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;

配置您的客戶端物件:

private static String REGION_ID = "YOUR REGION";
private static String ACCESS_ID = "YOUR ID";
private static String ACCESS_KEY = "YOUR KEY";

IClientProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_ID, ACCESS_KEY);
IAcsClient client = new DefaultAcsClient(profile);
  • 其中AccessKeyIdAccessKeySecure是使用者訪問阿里雲Open API時的認證資訊,可以登陸阿里雲官方站後獲得。
  • 第三個引數是使用者訪問的資源所在的預設region-id,參照區域列表

使用SDK

基本流程

  • 根據應用場景選擇要呼叫的方法,申明其請求物件

    CreateStacksRequest describe = new CreateStacksRequest();
  • 按照引數設定要求設定請求的引數,具體的引數設定要求參見 API文件

    // header
    describe.putHeaderParameter("x-acs-region-id", "cn-beijing"); 
    
    // url, sdk request會有對應的方法
    describe.setName("Name") 
      
    // Content
    describe.setContent(content.getBytes("utf-8"), "utf-8", FormatType.JSON);
  • 獲取結果,為json字串,之後您可以根據您的需要進行處理

    HttpResponse response = client.doAction(describe);
    String stringContent = ParseContent(response);
    System.out.println(stringContent);

這裡我們列舉四個示例,示例中用到的其餘函式參見附件中的程式碼:

List Region

/*
 * List regions
 */
public static void ListRegions(IAcsClient client) {
    DescribeRegionsRequest describe = new DescribeRegionsRequest();
    
    try {
        HttpResponse response = client.doAction(describe);
        String stringContent = ParseContent(response);
        System.out.println(stringContent);
    
    }catch (ServerException e) {
        e.printStackTrace();
    } 
    catch (ClientException e) {
        e.printStackTrace();
    } 
}  

示例輸出:

{"Regions": [{"LocalName": "u534eu5317 1", "RegionId": "cn-qingdao"}, {"LocalName": "u534eu5317 2", "RegionId": "cn-beijing"}, {"LocalName": "u534eu5317 3", "RegionId": "cn-zhangjiakou"}, {"LocalName": "u534eu4e1c 1", "RegionId": "cn-hangzhou"}, {"LocalName": "u534eu4e1c 2", "RegionId": "cn-shanghai"}, {"LocalName": "u534eu5357 1", "RegionId": "cn-shenzhen"}, {"LocalName": "u9999u6e2f", "RegionId": "cn-hongkong"}, {"LocalName": "u4e9au592au4e1cu5317 1 (u4e1cu4eac)", "RegionId": "ap-northeast-1"}, {"LocalName": "u4e9au592au4e1cu5357 1 (u65b0u52a0u5761)", "RegionId": "ap-southeast-1"}, {"LocalName": "u4e9au592au4e1cu5357 2 (u6089u5c3c)", "RegionId": "ap-southeast-2"}, {"LocalName": "u7f8eu56fdu4e1cu90e8 1 (u5f17u5409u5c3cu4e9a)", "RegionId": "us-east-1"}, {"LocalName": "u7f8eu56fdu897fu90e8 1 (u7845u8c37)", "RegionId": "us-west-1"}, {"LocalName": "u4e2du4e1cu4e1cu90e8 1 (u8feau62dc)", "RegionId": "me-east-1"}, {"LocalName": "u6b27u6d32u4e2du90e8 1 (u6cd5u5170u514bu798f)", "RegionId": "eu-central-1"}]}

List Stacks

/*
 * List stacks
 */
public static void ListStacks(IAcsClient client) {      
    DescribeStacksRequest describe = new DescribeStacksRequest();
    
    // example for set parameters in header
    describe.putHeaderParameter("x-acs-region-id", "cn-beijing"); 
    
    // example for set parameters in url
    describe.setName("liyi_test_170615"); // if not set, list all stacks
    
    try {
        HttpResponse response = client.doAction(describe);
        String stringContent = ParseContent(response);
        System.out.println(stringContent);
    
    }catch (ServerException e) {
        e.printStackTrace();
    } 
    catch (ClientException e) {
        e.printStackTrace();
    } 
}

Validate Template

/*
 * Validate a template
 * Succeed: return template
 * Fail: return error infomation 
 */
public static void ValidateTemplate(IAcsClient client) {
    ValidateTemplateRequest describe = new ValidateTemplateRequest();
    
    // example for set parameters in content
    String content = "{"Template":" + readToString("C:\Users\quming.ly\Desktop\nodejs.json") + "}";
    try {
        describe.setContent(content.getBytes("utf-8"), "utf-8", FormatType.JSON);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    
    try {
        HttpResponse response = client.doAction(describe);
        String stringContent = ParseContent(response);
        System.out.println(stringContent);
    
    }catch (ServerException e) {
        e.printStackTrace();
    } 
    catch (ClientException e) {
        e.printStackTrace();
    } 
}

Create Stack

/*
 * Create a template
 * Succeed: return stack name and id
 * Fail: return error infomation 
 */
public static void CreateStack(IAcsClient client) {
    CreateStacksRequest describe = new CreateStacksRequest();
    
    // example for set parameters in header
    describe.putHeaderParameter("x-acs-region-id", "cn-beijing"); 
            
    // example for set parameters in content
    JSONObject object = new JSONObject(); 
    object.put("TimeoutMins", 60);
    object.put("Name", "JAVA_SDK_DEMO");
    object.put("Template",readToString("C:\Users\quming.ly\Desktop\template.json"));
    
    // The follow parameters are depend on your template
    JSONObject parameters = new JSONObject(); 
    parameters.put("DBUser", "Demo");
    parameters.put("DBPassword", "Demo123456");
    parameters.put("DBRootPassword", "Demo123456");
    parameters.put("InstancePassword", "Demo123456");
    
    object.put("Parameters", parameters);
    
    try {
        describe.setContent(object.toString().getBytes("utf-8"), "utf-8", FormatType.JSON);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        HttpResponse response = client.doAction(describe);
        String stringContent = ParseContent(response);
        System.out.println(stringContent);
    
    }catch (ServerException e) {
        e.printStackTrace();
    } 
    catch (ClientException e) {
        e.printStackTrace();
    } 
}

完整的工程程式碼見附件。


相關文章