阿里云资源编排服务 Java SDK使用入门

阿里云资源编排服务 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": "\u534e\u5317 1", "RegionId": "cn-qingdao"}, {"LocalName": "\u534e\u5317 2", "RegionId": "cn-beijing"}, {"LocalName": "\u534e\u5317 3", "RegionId": "cn-zhangjiakou"}, {"LocalName": "\u534e\u4e1c 1", "RegionId": "cn-hangzhou"}, {"LocalName": "\u534e\u4e1c 2", "RegionId": "cn-shanghai"}, {"LocalName": "\u534e\u5357 1", "RegionId": "cn-shenzhen"}, {"LocalName": "\u9999\u6e2f", "RegionId": "cn-hongkong"}, {"LocalName": "\u4e9a\u592a\u4e1c\u5317 1 (\u4e1c\u4eac)", "RegionId": "ap-northeast-1"}, {"LocalName": "\u4e9a\u592a\u4e1c\u5357 1 (\u65b0\u52a0\u5761)", "RegionId": "ap-southeast-1"}, {"LocalName": "\u4e9a\u592a\u4e1c\u5357 2 (\u6089\u5c3c)", "RegionId": "ap-southeast-2"}, {"LocalName": "\u7f8e\u56fd\u4e1c\u90e8 1 (\u5f17\u5409\u5c3c\u4e9a)", "RegionId": "us-east-1"}, {"LocalName": "\u7f8e\u56fd\u897f\u90e8 1 (\u7845\u8c37)", "RegionId": "us-west-1"}, {"LocalName": "\u4e2d\u4e1c\u4e1c\u90e8 1 (\u8fea\u62dc)", "RegionId": "me-east-1"}, {"LocalName": "\u6b27\u6d32\u4e2d\u90e8 1 (\u6cd5\u5170\u514b\u798f)", "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();
    } 
}

完整的工程代码见附件。

上一篇:【Android源码解析】 自定义可清除的输入框


下一篇:Reading:一款不错的Material Desgin风格的Kotlin版本的开源APP