本教程详细介绍如何使用Alibaba Cloud SDK for Java给SLB实例创建TCP监听。

前提条件

  • 使用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;

/**
 * 使用Java SDK给SLB实例创建TCP监听,创建完成后删除SLB实例。
 */
public class CreateTCPListenerDemo {

    // 定义允许最大重试次数为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 "RemoveBackendServersRequest"
     * @param "IAcsClient"
     * @return "RemoveBackendServersResponse"
     */
    private RemoveBackendServersResponse removeBackendServers(RemoveBackendServersRequest request, IAcsClient client) {
        // 定义一个计数器
        Integer counter = 0;
        // 声明方法返回参数
        RemoveBackendServersResponse acsResponse = null;
        // 如果当前计数counter小于最大允许次数,重复操作
        while (counter < MAX_TRY_TIME) {
            try {
                // 调用SDK发送请求
                acsResponse = client.getAcsResponse(request);
                return acsResponse;
            } catch (ClientException e) {
                e.printStackTrace();
            }
                // 发生调用异常,计数器自加1,进行下一次尝试调用
                counter += 1;
        }
        // 在尝试三次后抛出运行时异常
        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(
                "cn-zhangjiakou",// 地域ID
                "your-access-key-id",// 您的AccessKey ID
                "your-access-key-secret");// 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);

        CreateTCPListenerDemo createTCPListenerDemo = new CreateTCPListenerDemo();

        // 创建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 = createTCPListenerDemo.createLoadBalancer(createLoadBalancerRequest, client);
        System.out.println("-------------------------------createLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerResponse));

        // 添加后端服务器
        // 初始化addBackendServers方法入参对象
        AddBackendServersRequest addBackendServersRequest = new AddBackendServersRequest();
        // 获取createLoadBalancer方法返回结果中的loadBalancerId
        String loadBalancerId = createLoadBalancerResponse.getLoadBalancerId();
        // 设置添加到默认服务器组的ECS的实例ID和权重       
        List<Map<String,String>> backendServers = new ArrayList<>();
        Map<String,String> server1 = new HashMap<>();
        server1.put("ServerId","i-8vb3kvxtwrx50lqscsk0");
        server1.put("Weight","100");
        backendServers.add(server1);
        Map<String,String> server2 = new HashMap<>();
        server2.put("ServerId","i-8vb7sribf5t0gxxxxn4c");
        server2.put("Weight","100");
        backendServers.add(server2);
        addBackendServersRequest.setLoadBalancerId(loadBalancerId);
        addBackendServersRequest.setBackendServers(new Gson().toJson(backendServers));
        // 添加后端服务器
        AddBackendServersResponse addBackendServersResponse = createTCPListenerDemo.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 = createTCPListenerDemo.createTCPListener(createLoadBalancerTCPListenerRequest, client);
        System.out.println("-------------------------------createTCPListener-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerTCPListenerResponse));

        // 删除后端服务器
        // 初始化deleteLoadBalancer方法入参对象
        RemoveBackendServersRequest removeBackendServersRequest = new RemoveBackendServersRequest();
        // 设置负载均衡实例ID
        removeBackendServersRequest.setLoadBalancerId(loadBalancerId);
        // 设置要删除的后端服务器列表
        removeBackendServersRequest.setBackendServers(new Gson().toJson(backendServers));
        // 删除后端服务器
        RemoveBackendServersResponse removeBackendServersResponse = createTCPListenerDemo.removeBackendServers(removeBackendServersRequest, client);
        System.out.println("-------------------------------removeBackendServers-------------------------------");
        System.out.println(new Gson().toJson(removeBackendServersResponse));

        // 删除slb实例
        // 初始化deleteLoadBalancer方法入参对象
        DeleteLoadBalancerRequest deleteLoadBalancerRequest = new DeleteLoadBalancerRequest();
        // 设置负载均衡实例ID
        deleteLoadBalancerRequest.setLoadBalancerId(loadBalancerId);
        // 删除slb实例
        DeleteLoadBalancerResponse deleteLoadBalancerResponse = createTCPListenerDemo.deleteLoadBalancer(deleteLoadBalancerRequest, client);
        System.out.println("-------------------------------deleteLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(deleteLoadBalancerResponse));
    }


}

运行结果

正确的运行结果类似如下:
-------------------------------createLoadBalancer-------------------------------
{
    "requestId": "02B3CF9B-BBF7-4AEF-A9B9-EFFF8250442E",
    "loadBalancerId": "lb-8vb0w0iexxxxxxxxx8j9c",
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "address": "47.xx.xx103",
    "loadBalancerName": "SLB1",
    "vpcId": "",
    "vSwitchId": "",
    "networkType": "classic",
    "addressIPVersion": "ipv4"
}
-------------------------------addBackendServers-------------------------------
{
    "requestId": "9A943ED2-CD8E-417D-8E31-79112E3923A5",
    "loadBalancerId": "lb-8vb0w0iexxxxxxxx8j9c",
    "backendServers": [
        {
            "serverId": "i-8vb531chzxxxxxxxfw0",
            "weight": "100",
            "type": "ecs"
        },
        {
            "serverId": "i-8vbdorsyrxxxxxxx5m",
            "weight": "100",
            "type": "ecs"
        }
    ]
}
-------------------------------createTCPListener-------------------------------
{
    "requestId": "70068B79-0A56-41AA-B864-BEED369F1AB7"
}
-------------------------------removeBackendServers-------------------------------
{
    "requestId": "D55819D9-716C-4692-9DB3-F1A58E6FB052",
    "loadBalancerId": "lb-8vb0w0iexxxxxxx8j9c",
    "backendServers": []
}
-------------------------------deleteLoadBalancer-------------------------------
{
    "requestId": "99B47DC4-3455-4A21-8221-3C6E993A02C5"
}