13.9. 使用 Micrometer 和 Prometheus 来监控 school timetable OptaPlanner Java 应用程序


OptaPlanner 通过 Micrometer 公开指标数据,这是 Java 应用程序的指标检测库。您可以将 Micrometer 与 Prometheus 搭配使用以监控 school timetable 应用程序中 OptaPlanner solver。

先决条件

  • 您已使用 Java 创建 OptaPlanner school timetable 应用程序。
  • 已安装 Prometheus。有关安装 Prometheus 的详情,请查看 Prometheus 网站。

流程

  1. 将 Micrometer Prometheus 依赖项添加到 school timetable pom.xml 文件中,其中 & lt;MICROMETER_VERSION > 是您安装的 Micrometer 的版本:

    <dependency>
     <groupId>io.micrometer</groupId>
     <artifactId>micrometer-registry-prometheus</artifactId>
     <version><MICROMETER_VERSION></version>
    </dependency>
    注意

    还需要 micrometer-core 依赖项。但是,这个依赖项包含在 optaplanner-core 依赖项中,您不需要将其添加到 pom.xml 文件中。

  2. 将以下导入语句添加到 TimeTableApp.java 类中。

    import io.micrometer.core.instrument.Metrics;
    import io.micrometer.prometheus.PrometheusConfig;
    import io.micrometer.prometheus.PrometheusMeterRegistry;
  3. 将下面几行添加到 TimeTableApp.java 类的主方法的顶部,以便 Prometheus 可以从 com.sun.net.net.httpserver.HttpServer 中获取数据:

    PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
    
            try {
                HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
                server.createContext("/prometheus", httpExchange -> {
                    String response = prometheusRegistry.scrape();
                    httpExchange.sendResponseHeaders(200, response.getBytes().length);
                    try (OutputStream os = httpExchange.getResponseBody()) {
                        os.write(response.getBytes());
                    }
                });
    
                new Thread(server::start).start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
            Metrics.addRegistry(prometheusRegistry);
    
            solve();
        }
  4. 添加以下行,以控制解决时间。通过调整解决时间,您可以了解指标如何根据要解决的时间而变化。

    withTerminationSpentLimit(Duration.ofMinutes(5)));
  5. 启动 school timetable 应用。
  6. 在 Web 浏览器中打开 http://localhost:8080/prometheus,查看 Prometheus 中的可时间应用程序。
  7. 打开监控系统,查看您的 OptaPlanner 项目的指标。

    公开以下指标:

    • optaplanner_solver_errors_total :从测量开始解决时出现的错误总数。
    • optaplanner_solve_duration_seconds_active_count :当前解决的解决方法数量。
    • optaplanner_solve_duration_seconds_max: run time of longest-running currently active solver.
    • optaplanner_solve_duration_seconds_duration_sum:每个活动解决持续时间的总和。例如,如果存在两个活跃的 solvers,一个只运行三分钟,另一个为一分钟,总计解决时间为 4 分钟。
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部