本教程详细介绍如何使用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 --&gt;     <dependency&gt;         <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>     <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-cms -->     <dependency>         <groupId>com.aliyun</groupId>         <artifactId>aliyun-java-sdk-cms</artifactId>         <version>7.0.4</version>     </dependency> </dependencies>

代码示例

本文操作示例主要以代码形式体现,具体代码如下:

阿里云2000元代金券免费领,最新优惠1折抢购,2核4G云服务器仅799元/3年,新老用户同享,立即抢购>>>

import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.cms.model.v20190101.*; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.slb.model.v20140515.*; import com.google.gson.Gson; import java.util.List; import java.util.ArrayList; import java.util.UUID;  /**  * 查看SLB实例的监控参数并配置告警  */ public class SlbMonitorDemo {       // 定义允许最大重试次数为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 "DescribeMetricLastRequest"      * @param "IAcsClient"      * @return "DescribeMetricLastResponse"      */     private DescribeMetricLastResponse describeMetricLast(DescribeMetricLastRequest request, IAcsClient client) {         // 定义一个计数器         Integer counter = 0;         // 声明方法返回参数         DescribeMetricLastResponse 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 "PutResourceMetricRuleRequest"      * @param "IAcsClient"      * @return "PutResourceMetricRuleResponse"      */     private PutResourceMetricRuleResponse putResourceMetricRule(PutResourceMetricRuleRequest request, IAcsClient client) {// 定义一个计数器         Integer counter = 0;         // 声明方法返回参数         PutResourceMetricRuleResponse 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 "DeleteMetricRulesRequest"      * @param "IAcsClient"      * @return "DeleteMetricRulesResponse"      */     private DeleteMetricRulesResponse deleteMetricRules(DeleteMetricRulesRequest request, IAcsClient client) {         Integer counter = 0;         // 声明方法返回参数         DeleteMetricRulesResponse 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(                 "cn-zhangjiakou",// 地域ID                 "your-access-key-id",// 您的AccessKey ID                 "your-access-key-secret");// 您的AccessKey Secret         IAcsClient client = new DefaultAcsClient(profile);          SlbMonitorDemo slbMonitorDemo = new SlbMonitorDemo();          // 创建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 = slbMonitorDemo.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和权重                 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-8vb7sribf5t0g0qkpn4c");         server2.put("Weight","100");         backendServers.add(server2);         addBackendServersRequest.setLoadBalancerId(loadBalancerId);         addBackendServersRequest.setBackendServers(new Gson().toJson(backendServers));         // 添加后端服务器         AddBackendServersResponse addBackendServersResponse = slbMonitorDemo.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 = slbMonitorDemo.createTCPListener(createLoadBalancerTCPListenerRequest, client);         System.out.println("-------------------------------createTCPListener-------------------------------");         System.out.println(new Gson().toJson(createLoadBalancerTCPListenerResponse));          // 查询slb实例QPS使用率         // 初始化describeMetricLast方法入参对象         DescribeMetricLastRequest describeMetricLastRequest = new DescribeMetricLastRequest();         // 设置资源筛选条件         String dimensions = "[{"instanceId":""+loadBalancerId+""}]";         describeMetricLastRequest.setDimensions(dimensions);         // 监控数据所属产品命名空间         describeMetricLastRequest.setNamespace("acs_slb_dashboard");         // 监控项名称         describeMetricLastRequest.setMetricName("InstanceQpsUtilization");         // 调用监控数据查询方法         DescribeMetricLastResponse describeMetricLastResponse = slbMonitorDemo.describeMetricLast(describeMetricLastRequest, client);         System.out.println("-------------------------------describeMetricLast-------------------------------");         System.out.println(new Gson().toJson(describeMetricLastResponse));          // 创建告警规则         // 初始化putResourceMetricRule方法入参对象         PutResourceMetricRuleRequest putResourceMetricRuleRequest = new PutResourceMetricRuleRequest();         // 设置报警联系组         putResourceMetricRuleRequest.setContactGroups("测试报警联系人组");         // 设置监控项为InstanceQpsUtilization(QPS使用率)         putResourceMetricRuleRequest.setMetricName("InstanceQpsUtilization");         // 设置告警规则所属产品         putResourceMetricRuleRequest.setNamespace("acs_slb_dashboard");         // 需要报警的资源         putResourceMetricRuleRequest.setResources(dimensions);         // 设置报警规则名称         putResourceMetricRuleRequest.setRuleName("测试报警规则");         // 设置报警规则id         String uuid = UUID.randomUUID().toString().replaceAll("-","");         putResourceMetricRuleRequest.setRuleId(uuid);         // 设置warn级别报警统计方法         putResourceMetricRuleRequest.setEscalationsCriticalStatistics("Average");         // 设置报警比较符,GreaterThanOrEqualToThreshold:大于等于         putResourceMetricRuleRequest.setEscalationsCriticalComparisonOperator("GreaterThanOrEqualToThreshold");         // 设置报警阈值         putResourceMetricRuleRequest.setEscalationsCriticalThreshold("90");         // 设置报警重试次数         putResourceMetricRuleRequest.setEscalationsCriticalTimes(3);         // 调用创建告警规则方法         PutResourceMetricRuleResponse putResourceMetricRuleResponse = slbMonitorDemo.putResourceMetricRule(putResourceMetricRuleRequest, client);         System.out.println("-------------------------------putResourceMetricRule-------------------------------");         System.out.println(new Gson().toJson(putResourceMetricRuleResponse));          // 删除报警规则         DeleteMetricRulesRequest deleteMetricRulesRequest = new DeleteMetricRulesRequest();         // 设置报警规则的id         List<String> ids = new ArrayList<>();         ids.add(uuid);         deleteMetricRulesRequest.setIds(ids);         DeleteMetricRulesResponse deleteMetricRulesResponse = slbMonitorDemo.deleteMetricRules(deleteMetricRulesRequest, client);         System.out.println("-------------------------------deleteMetricRules-------------------------------");         System.out.println(new Gson().toJson(deleteMetricRulesResponse));          // 删除slb实例         // 初始化deleteLoadBalancer方法入参对象         DeleteLoadBalancerRequest deleteLoadBalancerRequest = new DeleteLoadBalancerRequest();         // 设置负载均衡实例id         deleteLoadBalancerRequest.setLoadBalancerId(loadBalancerId);         // 调用删除slb实例方法         DeleteLoadBalancerResponse deleteLoadBalancerResponse = slbMonitorDemo.deleteLoadBalancer(deleteLoadBalancerRequest, client);         System.out.println("-------------------------------deleteLoadBalancer-------------------------------");         System.out.println(new Gson().toJson(deleteLoadBalancerResponse));      }   }

运行结果

正确运行结果类似如下:

-------------------------------createLoadBalancer------------------------------- {   "requestId": "481E145C-2461-4D77-8785-24166116EF57",   "loadBalancerId": "lb-8vbrl8ogxxxxxxxxbaid2",   "resourceGroupId": "rg-acfxxxxxxxx6aiy",   "address": "47.xx.xx.47",   "loadBalancerName": "SLB2",   "vpcId": "",   "vSwitchId": "",   "networkType": "classic",   "addressIPVersion": "ipv4" } -------------------------------addBackendServers------------------------------- {   "requestId": "CE1BF66D-3FE6-455B-87E9-D824BC5CFA97",   "loadBalancerId": "lb-8vbrl8oxxxxxxxx7baid2",   "backendServers": [     {       "serverId": "i-8vb3kvxxxxxxxxxscsk0",       "weight": "100",       "type": "ecs"     },     {       "serverId": "i-8vb7sribxxxxxxxxpn4c",       "weight": "100",       "type": "ecs"     }   ] } -------------------------------createTCPListener------------------------------- {   "requestId": "0908E402-3C9E-4EBB-97E2-EF9FD0474C0D" } -------------------------------describeMetricLast------------------------------- {   "code": "200",   "requestId": "7F9E7EC5-A900-4D2A-8526-46B065C470E6",   "datapoints": "[]",   "period": "60",   "success": true } -------------------------------putResourceMetricRule------------------------------- {   "success": true,   "code": "200",   "message": "",   "requestId": "cb294611-7e2e-40e6-8285-3d7ca1a44d2b" } -------------------------------deleteMetricRules------------------------------- {   "success": true,   "code": "200",   "requestId": "28298EB5-69AF-48F7-BAFB-FB4DE7F7CC88" } -------------------------------deleteLoadBalancer------------------------------- {   "requestId": "CD714FC8-233D-45D9-890D-A9EA5259A2DC" }