你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Java 的 Azure 指标顾问客户端库 - 版本 1.1.19

Azure 指标顾问是一项新的认知服务,它使用基于时序的决策 AI 来识别和帮助排查联机服务事件,并通过自动化业务 dataFeedMetrics 的切片和切块来监视业务运行状况。

源代码 | 包 (Maven) | API 参考文档 | 产品文档 | 样品

入门

先决条件

添加包

包括 BOM 文件

请将 azure-sdk-bom 包含在项目中,以依赖于库的正式发布 (GA) 版本。 在以下代码段中,将 {bom_version_to_target} 占位符替换为版本号。 若要详细了解 BOM,请参阅 AZURE SDK BOM 自述文件

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

然后在依赖项部分中包括直接依赖项,不带版本标记,如下所示。

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-metricsadvisor</artifactId>
    </dependency>
</dependencies>

包括直接依赖项

如果要依赖于 BOM 中不存在的特定库版本,请将直接依赖项添加到项目,如下所示。 注意: 此版本面向 Azure 指标顾问服务 API 版本 v1.0。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-metricsadvisor</artifactId>
    <version>1.1.19</version>
</dependency>

创建“指标顾问”资源

验证客户端

若要与指标顾问服务交互,需要创建指标顾问客户端的实例。 可以使用 创建 MetricsAdvisorClientBuilder异步客户端和同步客户端。 调用 buildClient() 将创建同步客户端,而调用 buildAsyncClient 将创建其异步对应客户端。

查找终结点

可以在 Azure 门户或 AzureCLI 中找到指标顾问资源的终结点

# Get the endpoint for the resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "endpoint"

使用 MetricsAdvisorKeyCredential 创建 MetricsAdvisor 客户端

需要两个密钥才能对客户端进行身份验证:

  • 指标顾问资源的订阅密钥。 可以在 Azure 门户中资源的“密钥和终结点”部分中找到此密钥。
  • 指标顾问实例的 API 密钥。 可以在指标顾问的 Web 门户的左侧导航菜单中的 API 密钥中找到此内容。

获得两个密钥和终结点后,可以使用 MetricsAdvisorKeyCredential 类对客户端进行身份验证,如下所示:

使用 MetricsAdvisorKeyCredential 创建指标顾问客户端

MetricsAdvisorKeyCredential credential = new MetricsAdvisorKeyCredential("subscription_key", "api_key");
MetricsAdvisorClient metricsAdvisorClient = new MetricsAdvisorClientBuilder()
    .endpoint("{endpoint}")
    .credential(credential)
    .buildClient();

使用 MetricsAdvisorKeyCredential 创建指标管理客户端

MetricsAdvisorKeyCredential credential = new MetricsAdvisorKeyCredential("subscription_key", "api_key");
MetricsAdvisorAdministrationClient metricsAdvisorAdminClient =
    new MetricsAdvisorAdministrationClientBuilder()
        .endpoint("{endpoint}")
        .credential(credential)
        .buildClient();

使用 Azure 服务目录创建 MetricsAdvisor 客户端

适用于 Java 的 Azure SDK 支持 Azure 标识包,因此可以轻松地从Microsoft 标识平台获取凭据。

使用 AAD 进行身份验证需要一些初始设置:

  • 添加 Azure 标识包
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.7.3</version>
</dependency>

设置完成后,可以从 azure.identity 中选择要使用的 凭据 类型。 例如, 可以使用 DefaultAzureCredential 对客户端进行身份验证:将 AAD 应用程序的客户端 ID、租户 ID 和客户端密码的值设置为环境变量:AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET。

使用 DefaultAzureCredential 进行授权最简单。 它会找到在其运行环境中使用的最佳凭据。 有关将 Azure Active Directory 授权与指标顾问配合使用的详细信息,请参阅 相关文档

使用 AAD 身份验证创建指标顾问客户端

TokenCredential credential = new DefaultAzureCredentialBuilder().build();
MetricsAdvisorClient metricsAdvisorClient = new MetricsAdvisorClientBuilder()
    .endpoint("{endpoint}")
    .credential(credential)
    .buildClient();

使用 AAD 身份验证创建指标管理客户端

TokenCredential credential = new DefaultAzureCredentialBuilder().build();
MetricsAdvisorAdministrationClient metricsAdvisorAdminClient =
    new MetricsAdvisorAdministrationClientBuilder()
        .endpoint("{endpoint}")
        .credential(credential)
        .buildClient();

关键概念

MetricsAdvisorClient

MetricsAdvisorClient 帮助:

  • 诊断异常和事件,并帮助分析事件的根本原因。
  • 检索服务扩充的原始时序数据和时序数据。
  • 通过多个通知挂钩发送实时警报。
  • 使用反馈调整异常/事件检测以优化模型。

MetricsAdvisorAdministrationClient

MetricsAdvisorAdministrationClient 允许你

  • 管理数据馈送
  • 列出可用指标及其检测配置
  • 微调异常情况检测配置
  • 配置异常警报配置
  • 管理通知挂钩

数据馈送

数据馈送是指标顾问从用户指定的数据源(例如 Cosmos 结构流、SQL 查询结果等)中引入的内容。 它包含时间戳行、零个或多个维度、一个或多个指标。 因此,多个指标可以共享相同的数据源,甚至相同的数据馈送。

数据馈送指标

指标是一种可量化的度量值,用于跟踪和评估特定业务流程的状态。 它可以是多个时序值(除以维度)的组合,例如,Web 垂直市场和 en-us 市场的用户计数。

数据馈送维度

维度是所提供的数据馈送的一个或多个分类值。 这些值的组合标识特定的单变量时序,例如国家/地区、语言、租户等等。

指标系列

指标系列是按时间顺序 (或列出或绘制) 索引的一系列数据点。 大多数情况下,时序是在连续相等间隔的时间点拍摄的序列。 因此,它是离散时间数据的序列。

异常情况检测配置

异常情况检测配置是为时序提供的一种配置,用于标识数据点是否被检测为异常。 指标可以应用一个或多个检测配置。 虽然默认检测配置会自动应用于名为“Default”) 的每个指标 (,但我们可以通过创建自定义异常情况检测配置来优化数据上使用的检测模式。

异常事件

当事件具有异常时,会根据应用的异常情况检测配置为系列生成事件。 指标顾问服务将指标中的一系列异常分组到事件中。

异常警报

可以将异常警报配置为在满足某些异常时触发。 可以使用不同的设置设置多个警报。 例如,可以为业务影响较小的异常创建 anomalyAlert,为更重要的警报创建另一个异常。

通知挂钩

通知挂钩是允许用户订阅实时警报的入口点。 这些警报使用 Hook 通过 Internet 发送。

示例

从示例或数据源添加数据馈送

此示例将用户指定的 SQLServerDataFeedSource 数据源数据引入服务。

DataFeed dataFeed = new DataFeed()
    .setName("dataFeedName")
    .setSource(new MySqlDataFeedSource("conn-string", "query"))
    .setGranularity(new DataFeedGranularity().setGranularityType(DataFeedGranularityType.DAILY))
    .setSchema(new DataFeedSchema(
        Arrays.asList(
            new DataFeedMetric("cost"),
            new DataFeedMetric("revenue")
        )).setDimensions(
        Arrays.asList(
            new DataFeedDimension("city"),
            new DataFeedDimension("category")
        ))
    )
    .setIngestionSettings(new DataFeedIngestionSettings(OffsetDateTime.parse("2020-01-01T00:00:00Z")))
    .setOptions(new DataFeedOptions()
        .setDescription("data feed description")
        .setRollupSettings(new DataFeedRollupSettings()
            .setRollupType(DataFeedRollupType.AUTO_ROLLUP)));
final DataFeed createdSqlDataFeed = metricsAdvisorAdminClient.createDataFeed(dataFeed);

System.out.printf("Data feed Id : %s%n", createdSqlDataFeed.getId());
System.out.printf("Data feed name : %s%n", createdSqlDataFeed.getName());
System.out.printf("Is the query user is one of data feed administrator : %s%n", createdSqlDataFeed.isAdmin());
System.out.printf("Data feed created time : %s%n", createdSqlDataFeed.getCreatedTime());
System.out.printf("Data feed granularity type : %s%n",
    createdSqlDataFeed.getGranularity().getGranularityType());
System.out.printf("Data feed granularity value : %d%n",
    createdSqlDataFeed.getGranularity().getCustomGranularityValue());
System.out.println("Data feed related metric Ids:");
dataFeed.getMetricIds().forEach((metricId, metricName)
    -> System.out.printf("Metric Id : %s, Metric Name: %s%n", metricId, metricName));
System.out.printf("Data feed source type: %s%n", createdSqlDataFeed.getSourceType());

if (SQL_SERVER_DB == createdSqlDataFeed.getSourceType()) {
    System.out.printf("Data feed sql server query: %s%n",
        ((SqlServerDataFeedSource) createdSqlDataFeed.getSource()).getQuery());
}

检查引入状态

此示例检查以前提供的数据馈送源的引入状态。

String dataFeedId = "3d48er30-6e6e-4391-b78f-b00dfee1e6f5";

metricsAdvisorAdminClient.listDataFeedIngestionStatus(
    dataFeedId,
    new ListDataFeedIngestionOptions(
        OffsetDateTime.parse("2020-01-01T00:00:00Z"),
        OffsetDateTime.parse("2020-09-09T00:00:00Z"))
).forEach(dataFeedIngestionStatus -> {
    System.out.printf("Message : %s%n", dataFeedIngestionStatus.getMessage());
    System.out.printf("Timestamp value : %s%n", dataFeedIngestionStatus.getTimestamp());
    System.out.printf("Status : %s%n", dataFeedIngestionStatus.getStatus());
});

配置异常情况检测配置

此示例演示用户如何为其数据配置异常情况检测配置。

String metricId = "3d48er30-6e6e-4391-b78f-b00dfee1e6f5";

ChangeThresholdCondition changeThresholdCondition = new ChangeThresholdCondition(
    20,
    10,
    true,
    AnomalyDetectorDirection.BOTH,
    new SuppressCondition(1, 2));

HardThresholdCondition hardThresholdCondition = new HardThresholdCondition(
    AnomalyDetectorDirection.DOWN,
    new SuppressCondition(1, 1))
    .setLowerBound(5.0);

SmartDetectionCondition smartDetectionCondition = new SmartDetectionCondition(
    10.0,
    AnomalyDetectorDirection.UP,
    new SuppressCondition(1, 2));

final AnomalyDetectionConfiguration anomalyDetectionConfiguration =
    metricsAdvisorAdminClient.createDetectionConfig(
        metricId,
        new AnomalyDetectionConfiguration("My dataPoint anomaly detection configuration")
            .setDescription("anomaly detection config description")
            .setWholeSeriesDetectionCondition(
                new MetricWholeSeriesDetectionCondition()
                    .setChangeThresholdCondition(changeThresholdCondition)
                    .setHardThresholdCondition(hardThresholdCondition)
                    .setSmartDetectionCondition(smartDetectionCondition)
                    .setConditionOperator(DetectionConditionOperator.OR))
    );

添加用于接收异常警报的挂钩

此示例创建一个接收异常事件警报的电子邮件挂钩。

NotificationHook emailNotificationHook = new EmailNotificationHook("email Hook")
    .setDescription("my email Hook")
    .setEmailsToAlert(Collections.singletonList("alertme@alertme.com"))
    .setExternalLink("https://adwiki.azurewebsites.net/articles/howto/alerts/create-hooks.html");

final NotificationHook notificationHook = metricsAdvisorAdminClient.createHook(emailNotificationHook);
EmailNotificationHook createdEmailHook = (EmailNotificationHook) notificationHook;
System.out.printf("Email Hook Id: %s%n", createdEmailHook.getId());
System.out.printf("Email Hook name: %s%n", createdEmailHook.getName());
System.out.printf("Email Hook description: %s%n", createdEmailHook.getDescription());
System.out.printf("Email Hook external Link: %s%n", createdEmailHook.getExternalLink());
System.out.printf("Email Hook emails to alert: %s%n",
    String.join(",", createdEmailHook.getEmailsToAlert()));

配置异常警报配置

此示例演示用户如何为其数据中检测到的异常配置警报配置。

String detectionConfigurationId1 = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
String detectionConfigurationId2 = "3e58er30-6e6e-4391-b78f-b00dfee1e6f5";
String hookId1 = "5f48er30-6e6e-4391-b78f-b00dfee1e6f5";
String hookId2 = "8i48er30-6e6e-4391-b78f-b00dfee1e6f5";

final AnomalyAlertConfiguration anomalyAlertConfiguration
    = metricsAdvisorAdminClient.createAlertConfig(
        new AnomalyAlertConfiguration("My anomaly alert config name")
            .setDescription("alert config description")
            .setMetricAlertConfigurations(
                Arrays.asList(
                    new MetricAlertConfiguration(detectionConfigurationId1,
                        MetricAnomalyAlertScope.forWholeSeries()),
                    new MetricAlertConfiguration(detectionConfigurationId2,
                        MetricAnomalyAlertScope.forWholeSeries())
                        .setAlertConditions(new MetricAnomalyAlertConditions()
                            .setSeverityRangeCondition(new SeverityCondition(AnomalySeverity.HIGH,
                                AnomalySeverity.HIGH)))
                ))
            .setCrossMetricsOperator(MetricAlertConfigurationsOperator.AND)
            .setHookIdsToAlert(Arrays.asList(hookId1, hookId2)));

查询异常情况检测结果

此示例演示了用户如何查询为异常情况检测配置触发的警报,并获取该 anomalyAlert 的异常。

String alertConfigurationId = "9ol48er30-6e6e-4391-b78f-b00dfee1e6f5";
final OffsetDateTime startTime = OffsetDateTime.parse("2020-01-01T00:00:00Z");
final OffsetDateTime endTime = OffsetDateTime.parse("2020-09-09T00:00:00Z");
metricsAdvisorClient.listAlerts(
    alertConfigurationId,
        startTime, endTime)
    .forEach(alert -> {
        System.out.printf("AnomalyAlert Id: %s%n", alert.getId());
        System.out.printf("AnomalyAlert created on: %s%n", alert.getCreatedTime());

        // List anomalies for returned alerts
        metricsAdvisorClient.listAnomaliesForAlert(
            alertConfigurationId,
            alert.getId())
            .forEach(anomaly -> {
                System.out.printf("DataPoint Anomaly was created on: %s%n", anomaly.getCreatedTime());
                System.out.printf("DataPoint Anomaly severity: %s%n", anomaly.getSeverity().toString());
                System.out.printf("DataPoint Anomaly status: %s%n", anomaly.getStatus());
                System.out.printf("DataPoint Anomaly related series key: %s%n", anomaly.getSeriesKey().asMap());
            });
    });

疑难解答

常规

指标顾问客户端引发 HttpResponseException [异常][http_response_exception]。 例如,如果尝试提供非现有反馈 ID, HttpResponseException 则会引发并显示指示失败原因的错误。 在以下代码片段中,通过捕获异常并显示有关错误的其他信息来妥善处理该错误。

try {
    metricsAdvisorClient.getFeedback("non_existing_feedback_id");
} catch (HttpResponseException e) {
    System.out.println(e.getMessage());
}

启用客户端日志记录

适用于 Java 的 Azure SDK 提供一致的日志记录故事,可帮助排查应用程序错误并加快解决。 生成的日志会在到达终端状态之前捕获应用程序的流,以帮助查找根本问题。 有关启用 日志记录 的指南,请查看日志记录 Wiki。

默认的 HTTP 客户端

默认情况下,所有客户端库都使用 Netty HTTP 客户端。 添加上述依赖项会自动将客户端库配置为使用 Netty HTTP 客户端。 HTTP 客户端 Wiki 中详述了如何配置或更改 HTTP 客户端。

后续步骤

有关详细信息,请参阅 示例自述文件

异步 API

到目前为止显示的所有示例都使用同步 API,但我们也提供对异步 API 的完全支持。 你需要使用 MetricsAdvisorAsyncClient

MetricsAdvisorKeyCredential credential = new MetricsAdvisorKeyCredential("subscription_key", "api_key");
MetricsAdvisorAsyncClient metricsAdvisorAsyncClient = new MetricsAdvisorClientBuilder()
    .credential(credential)
    .endpoint("{endpoint}")
    .buildAsyncClient();

其他文档

有关 Azure 认知服务指标顾问的更多文档,请参阅 指标顾问文档

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。

此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。

曝光数