本教程详细介绍如何使用Alibaba Cloud SDK for Java克隆一个SLB实例。

前提条件

  • 使用Alibaba Cloud SDK for Java,您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Java,准确的SDK版本号,请参见阿里云开发工具包(SDK)
    <dependencies>
      <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
      <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.4.3</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-slb -->
      <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-slb</artifactId>
        <version>3.2.13</version>
      </dependency>
    </dependencies>

代码示例

本文操作示例主要以代码形式体现,具体代码如下:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.slb.model.v20140515.*;
import com.google.gson.Gson;


public class ConfigrationCloneDemo {

    // 定义允许最大重试次数为3
    private static Integer MAX_TRY_TIME = 3;

    /**
     * 创建负载均衡实例
     *
     * @param "CreateLoadBalancerRequest"
     * @param "IAcsClient"
     * @return "CreateLoadBalancerResponse"
     */
    private CreateLoadBalancerResponse createLoadBalancer(CreateLoadBalancerRequest request, IAcsClient client) {

        // 初始化返回对象
        CreateLoadBalancerResponse response = null;
        try {
            // 调用SDK发送请求
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            // 发生调用错误,抛出运行时异常
            throw new RuntimeException();
        }
        return response;
    }

    /**
     * 添加后端服务器
     *
     * @param "AddBackendServersRequest"
     * @param "IAcsClient"
     * @return "AddBackendServersResponse"
     */
    private AddBackendServersResponse addBackendServers(AddBackendServersRequest request, IAcsClient client) {
        // 定义一个计数器
        Integer counter = 0;
        // 声明方法返回参数
        AddBackendServersResponse acsResponse = null;
        // 如果当前计数counter小于最大允许次数,重复操作
        while (counter < MAX_TRY_TIME) {
            try {
                // 调用SDK发送请求
                acsResponse = client.getAcsResponse(request);
                return acsResponse;
            } catch (ClientException e) {
                e.printStackTrace();
            }
            // 发生调用异常,计数器自加1,进行下一次尝试调用
            counter++;
        }
        throw new RuntimeException();
    }

    /**
     * 创建tcp监听
     *
     * @param "CreateLoadBalancerTCPListenerRequest"
     * @param "IAcsClient"
     * @return "CreateLoadBalancerTCPListenerResponse"
     */
    private CreateLoadBalancerTCPListenerResponse createTCPListener(CreateLoadBalancerTCPListenerRequest request, IAcsClient client) {
        // 定义一个计数器
        Integer counter = 0;
        // 声明方法返回参数
        CreateLoadBalancerTCPListenerResponse response = null;
        // 如果当前计数counter小于最大允许次数,重复操作
        while (counter < MAX_TRY_TIME) {
            try {
                // 调用SDK发送请求
                response = client.getAcsResponse(request);
                return response;
            } catch (ClientException e) {
                e.printStackTrace();
            }
            // 发生调用异常,计数器自加1,进行下一次尝试调用
            counter++;
        }
        // 在尝试三次后抛出运行时异常
        throw new RuntimeException();
    }

    /**
     * 查询指定负载均衡实例的详细信息
     *
     * @param "DescribeLoadBalancerAttributeRequest"
     * @param "IAcsClient"
     * @return "DescribeLoadBalancerAttributeResponse"
     */
    private DescribeLoadBalancerAttributeResponse describeLoadBalancerAttribute(DescribeLoadBalancerAttributeRequest request, IAcsClient client) {
        // 定义一个计数器
        Integer counter = 0;
        // 声明方法返回参数
        DescribeLoadBalancerAttributeResponse response = null;
        // 如果当前计数counter小于最大允许次数,重复操作
        while (counter < MAX_TRY_TIME) {
            try {
                // 调用SDK发送请求
                response = client.getAcsResponse(request);
                return response;
            } catch (ClientException e) {
                e.printStackTrace();
            }
            // 发生调用异常,计数器自加1,进行下一次尝试调用
            counter++;
        }
        // 在尝试三次后抛出运行时异常
        throw new RuntimeException();
    }

    /**
     * 删除slb实例
     *
     * @param "DeleteLoadBalancerRequest"
     * @param "IAcsClient"
     * @return "DeleteLoadBalancerResponse"
     */
    private DeleteLoadBalancerResponse deleteLoadBalancer(DeleteLoadBalancerRequest request, IAcsClient client) {
        // 声明方法返回参数
        DeleteLoadBalancerResponse response = null;
        try {
            // 调用SDK发送请求
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            // 发生调用错误,抛出运行时异常
            throw new RuntimeException();
        }
        return response;
    }

    public static void main(String[] args) {
        // 设置鉴权参数,初始化客户端
        DefaultProfile profile = DefaultProfile.getProfile(
                "<your-region-id>",// 地域ID
                "<your-access-key-id>",// 您的AccessKey ID
                "<your-access-key-secret>");// 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);

        ConfigrationCloneDemo configrationCloneDemo = new ConfigrationCloneDemo();

        // 创建slb实例
        // 初始化创建SLB实例方法入参对象
        CreateLoadBalancerRequest createLoadBalancerRequest = new CreateLoadBalancerRequest();
        // 设置新建SLB实例的主可用区为cn-zhangjiakou-a
        createLoadBalancerRequest.setMasterZoneId("cn-zhangjiakou-a");
        // 设置新建SLB实例的备可用区为cn-zhangjiakou-b
        createLoadBalancerRequest.setSlaveZoneId("cn-zhangjiakou-b");
        // 设置新建SLB实例的名称为SLB1
        createLoadBalancerRequest.setLoadBalancerName("SLB1");
        // 设置新建SLB实例的计费类型为按量计费
        createLoadBalancerRequest.setPayType("PayOnDemand");
        // 设置新建SLB实例的规格为slb.s1.small
        createLoadBalancerRequest.setLoadBalancerSpec("slb.s1.small");
        // 调用创建slb实例方法
        CreateLoadBalancerResponse createLoadBalancerResponse = configrationCloneDemo.createLoadBalancer(createLoadBalancerRequest, client);
        System.out.println("-------------------------------createLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerResponse));

        String loadBalancerId = createLoadBalancerResponse.getLoadBalancerId();


        // 添加后端服务器
        // 初始化addBackendServers方法入参对象
        AddBackendServersRequest addBackendServersRequest = new AddBackendServersRequest();
        // 设置添加到默认服务器组的ECS的实例ID和权重
        List<Map<String,String>> backendServers = new ArrayList<>();
        Map<String,String> server1 = new HashMap<>();
        server1.put("ServerId","i-8vb3kvxtwrx50lqsxxxx");
        server1.put("Weight","100");
        backendServers.add(server1);
        Map<String,String> server2 = new HashMap<>();
        server2.put("ServerId","i-8vb7sribf5t0g0qkxxxx");
        server2.put("Weight","100");
        backendServers.add(server2);
        addBackendServersRequest.setLoadBalancerId(loadBalancerId);
        addBackendServersRequest.setBackendServers(new Gson().toJson(backendServers));
        // 添加后端服务器
        AddBackendServersResponse addBackendServersResponse = configrationCloneDemo.addBackendServers(addBackendServersRequest, client);
        System.out.println("-------------------------------addBackendServers-------------------------------");
        System.out.println(new Gson().toJson(addBackendServersResponse));

        // 创建tcp监听
        // 初始化createTCPListener方法入参对象
        CreateLoadBalancerTCPListenerRequest createLoadBalancerTCPListenerRequest = new CreateLoadBalancerTCPListenerRequest();
        // 设置负载均衡实例ID
        createLoadBalancerTCPListenerRequest.setLoadBalancerId(loadBalancerId);
        // 设置负载均衡实例前端使用的端口
        createLoadBalancerTCPListenerRequest.setListenerPort(80);
        // 设置负载均衡实例后端使用的端口
        createLoadBalancerTCPListenerRequest.setBackendServerPort(80);
        // 设置监听的健康检查协议
        createLoadBalancerTCPListenerRequest.setHealthCheckType("tcp");
        // 设置监听的带宽峰值,-1表示不限制带宽峰值
        createLoadBalancerTCPListenerRequest.setBandwidth(-1);
        // 创建tcp监听
        CreateLoadBalancerTCPListenerResponse createLoadBalancerTCPListenerResponse = configrationCloneDemo.createTCPListener(createLoadBalancerTCPListenerRequest, client);
        System.out.println("-------------------------------createTCPListener-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerTCPListenerResponse));

        // 查询slb实例
        // 初始化describeLoadBalancerAttribute方法入参对象
        DescribeLoadBalancerAttributeRequest describeLoadBalancerAttributeRequest = new DescribeLoadBalancerAttributeRequest();
        // 设置负载均衡实例ID
        describeLoadBalancerAttributeRequest.setLoadBalancerId(loadBalancerId);
        // 调用查询slb实例方法
        DescribeLoadBalancerAttributeResponse describeLoadBalancerAttributeResponse = configrationCloneDemo.describeLoadBalancerAttribute(describeLoadBalancerAttributeRequest, client);
        System.out.println("-------------------------------describeLoadBalancerAttribute-------------------------------");
        System.out.println(new Gson().toJson(describeLoadBalancerAttributeResponse));

        // 获取查询到的实例详细信息
        String masterZoneId = describeLoadBalancerAttributeResponse.getMasterZoneId();
        String slaveZoneId = describeLoadBalancerAttributeResponse.getSlaveZoneId();
        String payType = describeLoadBalancerAttributeResponse.getPayType();
        String resourceGroupId = describeLoadBalancerAttributeResponse.getResourceGroupId();
        String addressIPVersion = describeLoadBalancerAttributeResponse.getAddressIPVersion();
        String addressType = describeLoadBalancerAttributeResponse.getAddressType();
        String loadBalancerName = describeLoadBalancerAttributeResponse.getLoadBalancerName();
        String loadBalancerSpec = describeLoadBalancerAttributeResponse.getLoadBalancerSpec();

        // 克隆实例
        // 初始化创建SLB实例方法入参对象
        CreateLoadBalancerRequest createLoadBalancerRequestClone = new CreateLoadBalancerRequest();
        // 设置新建SLB实例的主可用区为cn-zhangjiakou-a
        createLoadBalancerRequestClone.setMasterZoneId(masterZoneId);
        // 设置新建SLB实例的备可用区为cn-zhangjiakou-b
        createLoadBalancerRequestClone.setSlaveZoneId(slaveZoneId);
        // 设置新建SLB实例的名称为SLB1
        createLoadBalancerRequestClone.setLoadBalancerName(loadBalancerName);
        // 设置新建SLB实例的计费类型为按量计费
        createLoadBalancerRequestClone.setPayType(payType);
        // 设置新建SLB实例的规格为slb.s1.small
        createLoadBalancerRequestClone.setLoadBalancerSpec(loadBalancerSpec);
        // 设置资源组id
        createLoadBalancerRequestClone.setResourceGroupId(resourceGroupId);
        // 设置网络地址版本
        createLoadBalancerRequestClone.setAddressIPVersion(addressIPVersion);
        // 设置网络类型
        createLoadBalancerRequestClone.setAddressType(addressType);
        // 调用创建slb实例方法
        CreateLoadBalancerResponse createLoadBalancerResponseClone = configrationCloneDemo.createLoadBalancer(createLoadBalancerRequestClone, client);
        System.out.println("-------------------------------createLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerResponseClone));

        // 获取克隆实例的ID
        String loadBalancerIdClone = createLoadBalancerResponseClone.getLoadBalancerId();

        // 查询克隆出来的信息
        DescribeLoadBalancerAttributeRequest describeLoadBalancerAttributeRequestClone = new DescribeLoadBalancerAttributeRequest();
        describeLoadBalancerAttributeRequestClone.setLoadBalancerId(loadBalancerIdClone);
        DescribeLoadBalancerAttributeResponse describeLoadBalancerAttributeResponseClone = configrationCloneDemo.describeLoadBalancerAttribute(describeLoadBalancerAttributeRequestClone, client);
        System.out.println("-------------------------------describeLoadBalancerAttribute-------------------------------");
        System.out.println(new Gson().toJson(describeLoadBalancerAttributeResponseClone));

        // 删除第一个实例
        DeleteLoadBalancerRequest deleteLoadBalancerRequest = new DeleteLoadBalancerRequest();
        deleteLoadBalancerRequest.setLoadBalancerId(loadBalancerId);
        DeleteLoadBalancerResponse deleteLoadBalancerResponse = configrationCloneDemo.deleteLoadBalancer(deleteLoadBalancerRequest, client);
        System.out.println("-------------------------------deleteLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(deleteLoadBalancerResponse));

        // 删除克隆实例
        DeleteLoadBalancerRequest deleteLoadBalancerRequestClone = new DeleteLoadBalancerRequest();
        deleteLoadBalancerRequestClone.setLoadBalancerId(loadBalancerIdClone);
        DeleteLoadBalancerResponse deleteLoadBalancerResponseClone = configrationCloneDemo.deleteLoadBalancer(deleteLoadBalancerRequestClone, client);
        System.out.println("-------------------------------deleteLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(deleteLoadBalancerResponseClone));

    }
}

运行结果

正确的运行结果类似如下:
-------------------------------createLoadBalancer-------------------------------
{
    "requestId": "20ECBAE0-A670-47EE-AF0A-B7A1B7ED4B68",
    "loadBalancerId": "lb-8vb6ntaxxxxxxxzfxe7d",
    "resourceGroupId": "rg-acfxxxxxxxh6aiy",
    "address": "39.xx.xx232",
    "loadBalancerName": "SLB2",
    "vpcId": "",
    "vSwitchId": "",
    "networkType": "classic",
    "addressIPVersion": "ipv4"
}
-------------------------------addBackendServers-------------------------------
{
    "requestId": "B943BBBC-ACFD-483C-8B9A-9B6378578C0E",
    "loadBalancerId": "lb-8vb6ntxxxxxxx6zfxe7d",
    "backendServers": [
        {
            "serverId": "i-8vb3kvxxxxxxxxqscsk0",
            "weight": "100",
            "type": "ecs"
        },
        {
            "serverId": "i-8vb7srixxxxxxxxkpn4c",
            "weight": "100",
            "type": "ecs"
        }
    ]
}
-------------------------------createTCPListener-------------------------------
{
    "requestId": "47C51864-80DA-4C0F-8CA7-1D0F3A0F1CE5"
}
-------------------------------describeLoadBalancerAttribute-------------------------------
{
    "requestId": "EDDE6750-55BA-40DA-B23A-13902C8B5841",
    "loadBalancerId": "lb-8vb6ntxxxxxxx6zfxe7d",
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "loadBalancerName": "SLB2",
    "loadBalancerStatus": "inactive",
    "regionId": "cn-zhangjiakou",
    "regionIdAlias": "cn-zhangjiakou",
    "address": "39.xx.xx.232",
    "addressType": "internet",
    "vpcId": "",
    "vSwitchId": "",
    "networkType": "classic",
    "internetChargeType": "paybytraffic",
    "bandwidth": 5120,
    "loadBalancerSpec": "slb.s1.small",
    "createTime": "2019-09-25T08:55:44Z",
    "createTimeStamp": 1569401744000,
    "endTime": "2999-09-08T16:00:00Z",
    "endTimeStamp": 32493801600000,
    "payType": "PayOnDemand",
    "masterZoneId": "cn-zhangjiakou-a",
    "slaveZoneId": "cn-zhangjiakou-b",
    "addressIPVersion": "ipv4",
    "hasReservedInfo": "false",
    "deleteProtection": "off",
    "listenerPortsAndProtocal": [
        {
            "listenerPort": 80,
            "listenerProtocal": "tcp"
        }
    ],
    "listenerPortsAndProtocol": [
        {
            "listenerPort": 80,
            "listenerProtocol": "tcp"
        }
    ],
    "backendServers": [
        {
            "serverId": "i-8vb3kvxxxxxxxxxscsk0",
            "weight": 100,
            "type": "ecs"
        },
        {
            "serverId": "i-8vb7srixxxxxxxxkpn4c",
            "weight": 100,
            "type": "ecs"
        }
    ],
    "listenerPorts": [
        "80"
    ]
}
-------------------------------createLoadBalancer-------------------------------
{
    "requestId": "D4261166-45D7-4350-BB7D-C9D7DE9B10BC",
    "loadBalancerId": "lb-8vb04iq5xxxxxxxx1kwa0",
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "address": "47.xx.xx.95",
    "loadBalancerName": "SLB2",
    "vpcId": "",
    "vSwitchId": "",
    "networkType": "classic",
    "addressIPVersion": "ipv4"
}
-------------------------------describeLoadBalancerAttribute-------------------------------
{
    "requestId": "380690DC-83AE-424E-BACF-283EA844B47B",
    "loadBalancerId": "lb-8vb04iq5xxxxxxxx1kwa0",
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "loadBalancerName": "SLB2",
    "loadBalancerStatus": "active",
    "regionId": "cn-zhangjiakou",
    "regionIdAlias": "cn-zhangjiakou",
    "address": "47.xx.xx.95",
    "addressType": "internet",
    "vpcId": "",
    "vSwitchId": "",
    "networkType": "classic",
    "internetChargeType": "paybytraffic",
    "bandwidth": 5120,
    "loadBalancerSpec": "slb.s1.small",
    "createTime": "2019-09-25T08:55:47Z",
    "createTimeStamp": 1569401747000,
    "endTime": "2999-09-08T16:00:00Z",
    "endTimeStamp": 32493801600000,
    "payType": "PayOnDemand",
    "masterZoneId": "cn-zhangjiakou-a",
    "slaveZoneId": "cn-zhangjiakou-b",
    "addressIPVersion": "ipv4",
    "hasReservedInfo": "false",
    "deleteProtection": "off",
    "listenerPortsAndProtocal": [],
    "listenerPortsAndProtocol": [],
    "backendServers": [],
    "listenerPorts": []
}
-------------------------------deleteLoadBalancer-------------------------------
{
    "requestId": "AD1FB7C6-2AA9-4624-A7F9-FEC2EEFFC776"
}
-------------------------------deleteLoadBalancer-------------------------------
{
    "requestId": "41EBF184-991F-4DF2-9FD4-B99DE5900B82"
}