18.9. 使用 Micrometer 和 Prometheus 来监控您的中级时间 OptaPlanner Java 应用程序
OptaPlanner 通过 Micrometer (Java 应用程序的指标检测库)公开指标。您可以将 Micrometer 与 Prometheus 搭配使用,以监控教育时应用程序中的 OptaPlanner solver。
先决条件
- 您已创建了带有 Java 的 OptaPlanner school timetable 应用程序。
- 已安装 Prometheus。有关安装 Prometheus 的详情,请查看 Prometheus 网站。
流程
将 Micrometer Prometheus 依赖项添加到 school timetable
pom.xml文件中,其中 <MICROMETER_VERSION> 是您安装的 Micrometer 的版本:<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> <version><MICROMETER_VERSION></version> </dependency>
注意还需要
micrometer-core依赖项。但是,这个依赖项包含在optaplanner-core依赖项中,因此您不需要将其添加到pom.xml文件中。将以下导入语句添加到
TimeTableApp.java类中。import io.micrometer.core.instrument.Metrics; import io.micrometer.prometheus.PrometheusConfig; import io.micrometer.prometheus.PrometheusMeterRegistry;
将以下行添加到
TimeTableApp.java类的主要方法的顶部,以便 Prometheus 可以在解决方案启动前从com.sun.net.httpserver.HttpServer中 scrap 数据: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(); }添加下面这行来控制解决时间。通过调整解决时间,您可以根据需要解决的时间来查看指标变化。
withTerminationSpentLimit(Duration.ofMinutes(5)));
- 启动 tutorial 时间表应用程序。
-
在 Web 浏览器中打开
http://localhost:8080/prometheus,在 Prometheus 中查看时间表应用程序。 打开您的监控系统,以查看您的 OptaPlanner 项目的指标。
公开以下指标:
-
optaplanner_solver_errors_total:自测量开始以来发生的错误总数。 -
optaplanner_solver_solve_duration_seconds_active_count:当前解决者的数量。 -
optaplanner_solver_solve_duration_seconds_max: 最长运行的当前活跃解析器的运行时。 -
optaplanner_solver_solve_duration_seconds_duration_sum:每个活跃解析器的 solve 持续时间的总和。例如,如果有两个活跃的解决问题,则运行三分钟,另一个在一分钟内,总解决时间为四分钟。
-