Spring Cloud Sleuth(服务跟踪) springboot案例
时间: 2024-02-26 15:52:24 浏览: 151
spring-boot2-sleuth-integration-demo:Spring Cloud Sleuth与Spring Boot 2功能端点的集成
好的,下面是一个使用Spring Cloud Sleuth进行服务跟踪的Spring Boot案例:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
```
2. 添加配置
在application.yml文件中添加以下配置:
```yaml
spring:
application:
name: sleuth-demo
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9411
```
其中,sleuth.sampler.probability配置为1.0表示采样率为100%。
3. 编写代码
编写一个Controller,调用其他服务:
```java
@RestController
public class MyController {
private final RestTemplate restTemplate;
public MyController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/hello")
public String hello() {
String result = restTemplate.getForObject("http://localhost:8080/world", String.class);
return "Hello " + result;
}
}
```
4. 启动服务
启动服务后,访问http://localhost:8080/hello,可以看到控制台输出类似于以下日志:
```
2021-05-28 11:08:26.306 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] c.e.sleuthdemo.controller.MyController : hello
2021-05-28 11:08:26.311 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : http://localhost:8080/world HTTP/1.1
2021-05-28 11:08:26.311 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : Content-Length: 0
2021-05-28 11:08:26.311 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : Host: localhost:8080
2021-05-28 11:08:26.316 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : HTTP/1.1 200
2021-05-28 11:08:26.316 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : Content-Type: application/json
2021-05-28 11:08:26.316 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : Transfer-Encoding: chunked
2021-05-28 11:08:26.316 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient : Date: Fri, 28 May 2021 03:08:26 GMT
2021-05-28 11:08:26.316 INFO [sleuth-demo,9c3a3f80e0516d7f,9c3a3f80e0516d7f,false] 14292 --- [nio-8080-exec-1] o.apache.http.client.HttpClient :
```
这里的日志中,sleuth-demo为当前服务名,9c3a3f80e0516d7f为当前请求的Trace ID,false表示当前请求没有被采样。
5. 查看服务跟踪
访问http://localhost:9411/zipkin/,可以看到服务跟踪页面。在搜索框中输入服务名(sleuth-demo),可以看到当前服务的请求链路和请求耗时等信息。
阅读全文