zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring Cloud Sleuth与Prometheus集成-示例

SpringCloud集成 示例 Prometheus Sleuth
2023-06-13 09:18:27 时间

现在,假设我们有一个简单的Spring Boot应用程序,其中有一个REST端点返回Hello World消息。我们将添加Sleuth跟踪和Prometheus指标,以记录应用性能并导出到Prometheus。

第一步:添加依赖项

在pom.xml中添加以下依赖项:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

第二步:添加Prometheus配置

在application.yml中添加以下配置:

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    prometheus:
      enabled: true
  metrics:
    tags:
      application: ${spring.application.name}
  export:
    prometheus:
      enabled: true

第三步:启用Sleuth跟踪

在主类上添加@EnableSleuth注释:

@SpringBootApplication
@EnableSleuth
public class SleuthPrometheusDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SleuthPrometheusDemoApplication.class, args);
    }

}

第四步:添加指标注释

在HelloController类中添加@Timed注释:

@RestController
public class HelloController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/")
    @Timed(value = "hello.request.time", description = "Time taken to return Hello World message")
    public String hello() {
        LOGGER.info("Saying hello...");
        return "Hello World!";
    }
}

上面的@Timed注释将记录请求处理时间,并将其导出为名为hello.request.time的Prometheus指标。

第五步:启动应用程序

在启动应用程序之后,可以使用以下URL访问Prometheus端点:

http://localhost:8080/actuator/prometheus

Prometheus端点将返回当前应用程序的所有指标数据。可以使用Prometheus查询语言(PromQL)来查询和可视化指标数据。例如,要查看hello.request.time指标的平均值:

avg(hello_request_time)

可以使用Prometheus的Grafana插件将指标数据可视化。在Grafana中创建一个新的仪表板,并添加一个新的“Prometheus”数据源,然后使用PromQL查询语言构建图表和仪表板面板。