Java SDK general workflow and examples

Updated at:
Copy as MD

This topic describes the general procedure for using the Auto Scaling SDK for Java with an example of how to query ECS instances in a scaling group.

Background information

  • Alibaba Cloud Developer Center provides the Auto Scaling SDK for Java and the Maven project dependencies for the Alibaba Cloud SDK core library. You can write code to call Alibaba Cloud SDKs to access Alibaba Cloud products and services.

  • The example in this topic shows how to query a list of ECS instances in a scaling group. For more information about scaling groups, see Overview of scaling groups.

  • The methods, classes, and objects differ between older and newer SDK versions. If you are using an older SDK version, we recommend that you switch to the latest version to access the newest features.

Prerequisites

  • Create an AccessKey, which consists of an AccessKey ID and an AccessKey secret. For information about how to create and obtain an AccessKey, see Create an AccessKey.

    Important
    • To protect your Alibaba Cloud account's AccessKey, we recommend that you create a RAM user, grant the RAM user the required permissions, and then use the AccessKey of the RAM user to call the SDK. For more information, see System policies for Auto Scaling.

    • The AccessKey secret of a RAM user is displayed only when you create the AccessKey. It cannot be retrieved after creation.

  • Configure environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows. This topic uses the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to configure authentication for the Alibaba Cloud Credentials tool. This method allows you to access Alibaba Cloud APIs without hard-coding your AccessKey.

  • Download and install Java Development Kit (JDK) 1.8 or later. If it is not installed, see Install the JDK on Windows.

Use the Auto Scaling SDK

Manually add dependencies

Use the Auto Scaling SDK for Java to query the list of ECS instances in a scaling group.

Step 1: Install the Java SDK

  1. Use one of the following methods to configure the Maven project management tool in IntelliJ IDEA.

    • Method 1: Use the Maven project management tool that is integrated into IntelliJ IDEA.

    • Method 2: Go to the official Maven download page (Download Apache Maven) to download and manually configure the Maven tool.

  2. Go to Alibaba Cloud SDK Center, select Auto Scaling as the cloud product, and obtain the Maven project dependencies for the Alibaba Cloud SDK core library and Auto Scaling.

  3. Create a Maven project by using one of the following methods.

    • Method 1: Create a Maven project in IntelliJ IDEA. Open the New Project dialog box, select Maven from the project type list, set Project SDK to your installed JDK version, such as 1.8, and then click Next to complete the configuration.

    • Method 2: Convert an existing project to a Maven project.

      1. Right-click the project that you want to convert and select Add Framework Support....

      2. Select Maven and click OK.

  4. In your project's pom.xml file, create a <dependencies></dependencies> tag and add the following dependencies within it.

    After you add the dependencies, click the refresh icon in the upper-right corner, or right-click the project name and choose to download the Maven dependencies to your project.

    Note

    Obtain the latest dependencies from the official Alibaba Cloud SDK website.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-openapi</artifactId>
      <version>0.2.8</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>ess20220222</artifactId>
      <version>1.5.2</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>credentials-java</artifactId>
      <version>0.2.11</version>
    </dependency>

Step 2: Write code

This step demonstrates the general workflow for using the Auto Scaling SDK for Java by using the DescribeScalingInstances operation to query ECS instances in a scaling group.

  1. Use the Credentials tool to obtain credentials from your environment variables.

    Sample code:

    com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
    com.aliyun.teaopenapi.models.Config config = new Config();
    config.setCredential(credentialClient);
    config.setEndpoint("ess.aliyuncs.com");
  2. Create a client object.

    Sample code:

    com.aliyun.ess20220222.Client client = new com.aliyun.ess20220222.Client(config);
  3. Create a Request object for the operation. Its constructor generates a default request object.

    The class is named by appending Request to the API operation name. For example, if the API operation to query the list of ECS instances in a scaling group is DescribeScalingInstances, the corresponding request class is named DescribeScalingInstancesRequest.

    DescribeScalingInstancesRequest request = new DescribeScalingInstancesRequest();
  4. Set the parameters for the request object.

    Use the setXxx method of the request class to set the required information, which are the mandatory parameters for the API. Use the setXxx method to set the parameters. In the example:

    • The RegionId parameter of the DescribeScalingInstances API operation specifies the region.

    • The InstanceId parameter of the DescribeScalingInstances API operation specifies the ID of the ECS instance to query. Setting setInstanceId to i-bp15itgtxemxy7v9**** specifies the query target as instance i-bp15itgtxemxy7v9****.

    request.setInstanceId("i-bp15itgtxemxy7v9****");
  5. Call the describeScalingInstancesWithOptions method of the client object to get the response for the request.

    Sample code:

    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    DescribeScalingInstancesResponse response = client.describeScalingInstancesWithOptions(request,runtime);
    Note

    For more information, go to the Auto Scaling SDK Center in the Alibaba Cloud OpenAPI Developer Portal, click the Java tab, go to the Quick Start section, and then click Procedure.

Complete code example

The following code provides the complete Java SDK example for this topic.

import com.aliyun.ess20220222.models.DescribeScalingInstancesRequest;
import com.aliyun.ess20220222.models.DescribeScalingInstancesResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class DescribeScalingInstances {
    public static void main(String[] args) throws Exception {
        // Use the default credential provider to create a client.
        // For more information, see https://github.com/aliyun/credentials-java/blob/master/README-EN.md
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new Config();
        config.setCredential(credentialClient);
        // Specify the endpoint of the service.
        config.setEndpoint("ess.aliyuncs.com");
        com.aliyun.ess20220222.Client client = new com.aliyun.ess20220222.Client(config);
        DescribeScalingInstancesRequest request = new DescribeScalingInstancesRequest();
        request.setRegionId("cn-hangzhou");
        request.setScalingGroupId("asg-XXXXXXXX");
        request.setScalingConfigurationId("asc-XXXXXXXXX");
        request.setPageNumber(1);
        request.setPageSize(10);
        List<String> instanceIdList = new ArrayList<String>();
        instanceIdList.add("i-XXXXXX");
        request.setInstanceIds(instanceIdList);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        DescribeScalingInstancesResponse response = client.describeScalingInstancesWithOptions(request,runtime);
        System.out.println(new Gson().toJson(response));
    }
}

Sample response

A successful request returns a response similar to the following example:

{
    "TotalCount": 2,
    "RequestId": "5E65F238-4B45-54B6-BE15-A34956FA0D96",
    "PageSize": 10,
    "PageNumber": 1,
    "ScalingInstances": {
        "ScalingInstance": [
            {
                "LoadBalancerWeight": 50,
                "CreatedTime": "2022-04-27T03:24:58Z",
                "WarmupState": "NoNeedWarmup",
                "ZoneId": "cn-hangzhou-i",
                "InstanceId": "i-bp1h3dog530vvnqm****",
                "ScalingActivityId": "asa-bp16rgo6477ojn3u****",
                "ScalingGroupId": "asg-bp10uuhy2wbb2tip****",
                "CreationTime": "2022-04-27T03:24Z",
                "HealthStatus": "Healthy",
                "LifecycleState": "Protected",
                "Entrusted": false,
                "CreationType": "Attached"
            },
            {
                "LoadBalancerWeight": 50,
                "CreatedTime": "2022-04-27T06:38:21Z",
                "ZoneId": "cn-hangzhou-i",
                "InstanceId": "i-bp15itgtxemxy7v9****",
                "ScalingActivityId": "asa-bp1ejteup0bntltl****",
                "ScalingGroupId": "asg-bp10uuhy2wbb2tip****",
                "HealthStatus": "Healthy",
                "LifecycleState": "Stopped",
                "CreationType": "AutoCreated",
                "WarmupState": "NoNeedWarmup",
                "CreationTime": "2022-04-27T06:38Z",
                "Entrusted": true,
                "ScalingConfigurationId": "asc-bp1433dp4gktwkmi****"
            }
        ]
    },
    "TotalSpotCount": 0
}

OpenAPI Explorer

Use the Auto Scaling SDK for Java to create a scaling group.

Step 1: Get sample code

Use Alibaba Cloud OpenAPI Explorer to call Auto Scaling API operations and generate SDK sample code.

  1. Go to OpenAPI Explorer.

  2. Download the complete SDK project and decompress it.

At the top of the OpenAPI Explorer page, select the Auto Scaling service. In the API list on the left, find the CreateScalingGroup operation. In the Parameters section, specify the required parameters, such as ScalingGroupName, RegionId, MinSize, and MaxSize, and then click Send Request. On the right side, switch to the SDK Sample tab. Select an SDK version (we recommend V2.0) and a programming language, such as Java, Python, or Go, to view the automatically generated SDK sample code. Click the SDK Doc and SDK Installation links in the upper-right corner to download the complete SDK project.

Step 2: Run the sample code

  1. In IntelliJ IDEA, choose File > Open, select the unzipped project folder, and wait for Maven to automatically install the dependencies.

  2. Run the sample code.

    Double-click Sample. If no errors are reported, run the code.

  3. View the result.

    Go to the Auto Scaling console to view the newly created scaling group.

Complete code example

For a complete example of using the Java SDK to create a scaling group, see Java SDK Example.

Next steps

A scaling group does not take effect immediately after it is created. You must call EnableScalingGroup to enable the scaling group, which allows it to trigger scaling activities and execute scaling rules.

Related documentation