本教程详细介绍如何使用Alibaba Cloud SDK for Java给一个SLB实例创建一个HTTPS监听,并更新该实例下HTTPS监听使用的服务器证书。

前提条件

在使用本教程前,请确保已完成以下操作:
  • 使用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 UploadServerCertificateDemo {

    // 定义允许最大重试次数为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();

    }

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

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

    /**
     * 修改HTTPS监听的配置
     *
     * @param "SetLoadBalancerHTTPSListenerAttributeRequest"
     * @param "IAcsClient"
     * @return "SetLoadBalancerHTTPSListenerAttributeResponse"
     */
    private SetLoadBalancerHTTPSListenerAttributeResponse setHttpsListenerAttribute(SetLoadBalancerHTTPSListenerAttributeRequest request, IAcsClient client) {
        // 定义一个计数器
        Integer counter = 0;
        // 声明方法返回参数
        SetLoadBalancerHTTPSListenerAttributeResponse 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(
                "<your-region-id>",// 地域ID
                "your-access-key-id",// 您的AccessKey ID
                "your-access-key-secret");// 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);

        UploadServerCertificateDemo uploadServerCertificateDemo = new UploadServerCertificateDemo();

        // 创建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("SLB2");
        // 设置新建SLB实例的计费类型为按量计费
        createLoadBalancerRequest.setPayType("PayOnDemand");
        // 设置新建SLB实例的规格为slb.s1.small
        createLoadBalancerRequest.setLoadBalancerSpec("slb.s1.small");
        // 调用创建slb实例方法
        CreateLoadBalancerResponse createLoadBalancerResponse = uploadServerCertificateDemo.createLoadBalancer(createLoadBalancerRequest, client);
        System.out.println("-------------------------------createLoadBalancer-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerResponse));

        // 获取createLoadBalancer方法返回结果中的loadBalancerId
        String loadBalancerId = createLoadBalancerResponse.getLoadBalancerId();

        // 添加后端服务器
        // 初始化addBackendServers方法入参对象
        AddBackendServersRequest addBackendServersRequest = new AddBackendServersRequest();
        // 设置添加到默认服务器组的ECS的实例ID和权重
        String backendServers = "[{\"ServerId\":\"i-8vbdorsyxxxxxxnv6u5m\",\"Weight\":\"100\"},{\"ServerId\":\"i-8vb531xxxxxxx55dfw0\",\"Weight\":\"100\"}]";
        addBackendServersRequest.setLoadBalancerId(loadBalancerId);
        addBackendServersRequest.setBackendServers(backendServers);
        // 添加后端服务器
        AddBackendServersResponse addBackendServersResponse = uploadServerCertificateDemo.addBackendServers(addBackendServersRequest, client);
        System.out.println("-------------------------------addBackendServers-------------------------------");
        System.out.println(new Gson().toJson(addBackendServersResponse));

        // 上传服务器证书
        // 初始化uploadServerCertificate方法入参对象
        UploadServerCertificateRequest uploadServerCertificateRequest = new UploadServerCertificateRequest();
        // 要上传的公钥证书
        // uploadServerCertificateRequest.setServerCertificate("-----BEGIN CERTIFICATE-----xxxxxxx-----END CERTIFICATE-----");
        // 证书私钥
        // uploadServerCertificateRequest.setPrivateKey("-----BEGIN RSA PRIVATE KEY-----xxxxxxxxxxx-----END RSA PRIVATE KEY----");
        // 调用上传服务器证书方法
        UploadServerCertificateResponse uploadServerCertificateResponse = uploadServerCertificateDemo.uploadServerCertificate(uploadServerCertificateRequest, client);
        System.out.println("-------------------------------uploadServerCertificate-------------------------------");
        System.out.println(new Gson().toJson(uploadServerCertificateResponse));

        // 获取uploadServerCertificate方法返回的ServerCertificateId
        String serverCertificateId = uploadServerCertificateResponse.getServerCertificateId();

        // 创建https监听
        // 初始化createHttpsListener方法入参对象
        CreateLoadBalancerHTTPSListenerRequest createLoadBalancerHTTPSListenerRequest = new CreateLoadBalancerHTTPSListenerRequest();
        // 负载均衡实例的ID
        createLoadBalancerHTTPSListenerRequest.setLoadBalancerId(loadBalancerId);
        // 监听的带宽峰值
        createLoadBalancerHTTPSListenerRequest.setBandwidth(6);
        // 负载均衡实例前端使用的端口
        createLoadBalancerHTTPSListenerRequest.setListenerPort(80);
        // 是否开启健康检查
        createLoadBalancerHTTPSListenerRequest.setHealthCheck("off");
        // 是否开启会话保持
        createLoadBalancerHTTPSListenerRequest.setStickySession("off");
        // 负载均衡实例后端使用的端口
        createLoadBalancerHTTPSListenerRequest.setBackendServerPort(443);
        // 服务器证书的ID
        createLoadBalancerHTTPSListenerRequest.setServerCertificateId(serverCertificateId);
        CreateLoadBalancerHTTPSListenerResponse createLoadBalancerHTTPSListenerResponse = uploadServerCertificateDemo.createHttpsListener(createLoadBalancerHTTPSListenerRequest, client);
        System.out.println("-------------------------------createHttpsListener-------------------------------");
        System.out.println(new Gson().toJson(createLoadBalancerHTTPSListenerResponse));

        // 更新服务器证书
        // 初始化uploadServerCertificate方法入参对象
        UploadServerCertificateRequest uploadServerCertificateRequestNew = new UploadServerCertificateRequest();
        // 要上传的公钥证书
        // uploadServerCertificateRequestNew.setServerCertificate("-----BEGIN CERTIFICATE-----xxxxxxx-----END CERTIFICATE-----");
        // 证书私钥
        // uploadServerCertificateRequestNew.setPrivateKey("-----BEGIN RSA PRIVATE KEY-----xxxxxxxxxxx-----END RSA PRIVATE KEY----");
        // 调用上传服务器证书方法
        UploadServerCertificateResponse uploadServerCertificateResponseNew = uploadServerCertificateDemo.uploadServerCertificate(uploadServerCertificateRequestNew, client);
        System.out.println("-------------------------------uploadServerCertificate-------------------------------");
        System.out.println(new Gson().toJson(uploadServerCertificateResponseNew));


        // 更新服务器证书ID
        serverCertificateId = uploadServerCertificateResponseNew.getServerCertificateId();

        // 修改https监听配置
        // 初始化setHttpsListenerAttribute方法入参对象
        SetLoadBalancerHTTPSListenerAttributeRequest setLoadBalancerHTTPSListenerAttributeRequest = new SetLoadBalancerHTTPSListenerAttributeRequest();
        // 负载均衡实例的ID
        setLoadBalancerHTTPSListenerAttributeRequest.setLoadBalancerId(loadBalancerId);
        // 监听的带宽峰值
        setLoadBalancerHTTPSListenerAttributeRequest.setBandwidth(10);
        // 负载均衡实例前端使用的端口
        setLoadBalancerHTTPSListenerAttributeRequest.setListenerPort(80);
        // 是否开启健康检查
        setLoadBalancerHTTPSListenerAttributeRequest.setHealthCheck("on");
        // 健康检查超时时间
        setLoadBalancerHTTPSListenerAttributeRequest.setHealthCheckTimeout(3);
        // 健康检查的时间间隔
        setLoadBalancerHTTPSListenerAttributeRequest.setHealthCheckInterval(5);
        // 健康检查的成功重试次数,连续成功4次,将健康检查状态fail改为success
        setLoadBalancerHTTPSListenerAttributeRequest.setHealthyThreshold(4);
        // 健康检查的失败重试次数,连续失败4次,将健康检查状态success改为fail
        setLoadBalancerHTTPSListenerAttributeRequest.setUnhealthyThreshold(4);
        // 是否开启会话保持
        setLoadBalancerHTTPSListenerAttributeRequest.setStickySession("off");
        // 服务器证书的ID
        setLoadBalancerHTTPSListenerAttributeRequest.setServerCertificateId(serverCertificateId);
        // 调用更新https监听配置方法
        SetLoadBalancerHTTPSListenerAttributeResponse setLoadBalancerHTTPSListenerAttributeResponse = uploadServerCertificateDemo.setHttpsListenerAttribute(setLoadBalancerHTTPSListenerAttributeRequest, client);
        System.out.println("-------------------------------setHttpsListenerAttribute-------------------------------");
        System.out.println(new Gson().toJson(setLoadBalancerHTTPSListenerAttributeResponse));

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

}

运行结果

正确运行结果类似如下:

-------------------------------createLoadBalancer-------------------------------
{
    "requestId": "338C24ED-923C-4834-A4B1-0F8E345510D2",
    "loadBalancerId": "lb-8vba3rxxxxxxxxhznym79",
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "address": "39.xx.xx.28",
    "loadBalancerName": "SLB2",
    "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"
        }
    ]
}
-------------------------------uploadServerCertificate-------------------------------
{
    "requestId": "89BB7010-CD29-4922-B203-679B70AC305B",
    "serverCertificateId": "1231579085529123_xxxxxxxxxx_415862535_-491430299",
    "fingerprint": "54:14:5f:84:00:03:80:d8:cf:05:cf:xx:xx:xx:xx:75:c0:15:e7:5f",
    "serverCertificateName": "www.example.com",
    "regionId": "cn-zhangjiakou",
    "regionIdAlias": "cn-zhangjiakou",
    "aliCloudCertificateId": "",
    "aliCloudCertificateName": "",
    "isAliCloudCertificate": 0,
    "resourceGroupId": "rg-acfxxxxxxxx6aiy",
    "expireTime": "2020-09-23T12:00:00Z",
    "expireTimeStamp": 1600862400000,
    "commonName": "www.example.com",
    "subjectAlternativeNames": [
        "www.example.com"
    ]
}
-------------------------------createHttpsListener-------------------------------
{
    "requestId": "EFA657A7-23B9-41D2-9178-E8872B22389E"
}
-------------------------------uploadServerCertificate-------------------------------
{
    "requestId": "206881D7-A375-430B-AF3C-6EE457FF958A",
    "serverCertificateId": "1231579085529123_16d662baa04_-xxxxxxxxx_-1295811589",
    "fingerprint": "5a:46:76:18:93:f8:c4:49:xx:xx:xx:xx:xx:bf:30:63:91:68:8f:30",
    "serverCertificateName": "www.example.com",
    "regionId": "cn-zhangjiakou",
    "regionIdAlias": "cn-zhangjiakou",
    "aliCloudCertificateId": "",
    "aliCloudCertificateName": "",
    "isAliCloudCertificate": 0,
    "resourceGroupId": "rg-acfmxazb4ph6aiy",
    "expireTime": "2020-09-24T12:00:00Z",
    "expireTimeStamp": 1600948800000,
    "commonName": "www.example.com",
    "subjectAlternativeNames": [
        "www.example.com"
    ]
}
-------------------------------setHttpsListenerAttribute-------------------------------
{
    "requestId": "E183F981-2AAB-4F44-BF61-E59F755B02CC"
}
-------------------------------removeBackendServers-------------------------------
{
    "requestId": "D55819D9-716C-4692-9DB3-F1A58E6FB052",
    "loadBalancerId": "lb-8vb0w0iexxxxxxx8j9c",
    "backendServers": []
}
-------------------------------deleteLoadBalancer-------------------------------
{
    "requestId": "956BBCD8-27FA-4F25-AAAA-9598073D12F0"
}