SpringCloud 基础——Sleuth 链路追踪

源码地址:https://pan.baidu.com/s/1Hmvh1Bbss_Z1w1I7I1mwDw 提取码:e41h

随着业务的发展,系统规模越来越大,各微服务之间的调用关系也变得越来越错综复杂。一个客户端请求往往会在后端发生多次调用关系,这就形成了一条复杂的分布式服务调用链路。在任何一个环节发生延迟或错误,都可能导致请求失败。这个时候,链路的追踪变得越来越重要,通过服务的的调用链路追踪,我们可以更快速地发现错误根源,也可用来监控分析链路的性能。
springcloud 提供了 sleuth 组件为微服务架构提供了分布式服务跟踪的能力。
来看看如何使用 sleuth 组件追踪微服务的服务调用链路吧

创建 server-sleuth 服务

1. pom.xml

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.2.RELEASE
		 
	
	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.cloud
			spring-cloud-starter-eureka-server
			1.4.1.RELEASE
		
		
			io.zipkin.java
			zipkin-server
			2.8.4
		
		
			io.zipkin.java
			zipkin-autoconfigure-ui
			2.8.4
		
	
	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				Finchley.RELEASE
				pom
				import
			
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
				
					true
				
			
		
	
	
		
			spring-milestones
			Spring Milestones
			https://repo.spring.io/milestone
			
				false
			
		
	

(1)引入 zipkin-server 依赖和 zipkin-autoconfigure-ui 可视化监控组件
(2)这里我去掉了 test 依赖,因为 zipkin-server 依赖有个日志的 jar 包与 test 依赖的日志 jar 包重复,导致无法启动

2. application.properties

eureka.client.serviceUrl.defaultZone=http://localhost:7070/eureka/
server.port=7078
spring.application.name=sleuth
#zipkin启动报错无法访问的解决方法
management.metrics.web.server.auto-time-requests=false

3. 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import zipkin.server.internal.EnableZipkinServer;

@SpringBootApplication
@EnableEurekaClient
@EnableZipkinServer
public class SleuthApp {
	public static void main(String[] args) {
		SpringApplication.run(SleuthApp.class, args);
	}
}

加入 @EnableZipkinServer 注解
这时,启动注册中心和 server-sleuth 服务,输入 localhost:7078 ,可以看到如下界面

SpringCloud 基础——Sleuth 链路追踪_第1张图片
4. 给其他要追踪的服务加入相关配置
本例中分别给 serviceA1 和 service-rest 服务加上了 zipkin 依赖和如下两个配置
想要追踪哪个服务,就要给相关服务加上依赖和相关配置

		
            org.springframework.cloud
            spring-cloud-starter-zipkin
        
##加入zipkin链路追踪
spring.zipkin.base-url=http://localhost:7078
##有时候可能在zipkin服务器中看不到数据,那是因为默认sleuth收集信息的比率是0.1 
spring.sleuth.sampler.percentage=1.0

5. 链路追踪测试
先进行一次服务调用,输入 localhost:7073/getListRest,可以多试几次
再查看可视化链路监控台 localhost:7078,如下图
点击记录可查看各服务调用的耗时等信息,点击依赖分析,还可以查看服务调用链路
SpringCloud 基础——Sleuth 链路追踪_第2张图片
SpringCloud 基础——Sleuth 链路追踪_第3张图片
SpringCloud 基础——Sleuth 链路追踪_第4张图片

博主经验尚浅,也暂无微服务相关项目经验,如果理解不到位甚至理解错误,希望评论区讨论,请多指教!

你可能感兴趣的:(springcloud,零基础学,spring,cloud)