背景
微服务架构下,一个请求可能会经过多个服务才会得到结果,如果在这个过程中出现了异常,就很难去定位问题。所以,必须要实现一个分布式链路跟踪的功能,直观的展示出完整的调用过程。
什么是Spring Cloud Sleuth?
Spring Cloud Sleuth是Spring Cloud提供的分布式系统服务链追踪组件,它大量借用了Google的Dapper,Twitter的Zipkin。学习Spring Cloud Sleuth,最好先对Zipkin有一些了解,对span、trace这些概念有相应的认识。
如何使用Spring Cloud Sleuth?
在这里,为了复习下之前学过的Spring Cloud相关的组件,会通过之前搭建的多个服务来学习。
microservice-provider:服务提供者
microservice-consumer:服务消费者
Eureka Server:作为注册中心,提供服务注册和服务发现的功能。
microservice-gateway:微服务网关,所有的调用,都是经过网关进行转发
microservice-zipkin-server:收集调用信息,提供界面进行查看
microservice-provider,microservice-consumer,microservice-gateway和microservice-zipkin-server都向Eureka Server注册;
microservice-consumer调用microservice-provider时,通过microservice-gateway进行调用。访问microservice-consumer时,通过microservice-gateway访问。
microservice-provider,microservice-consumer,microservice-gateway都向microservice-zipkin-server上报调用信息。
Eureka Server:
pom文件:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置文件application.properties:
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Eureka Server启动端口为8761。
启动类:
@SpringBootApplication
@EnableEurekaServer//声明这是一个Eureka server
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
EurekaServerApplication上添加注解@EnableEurekaServer,声明这是一个Eureka server。
microservice-zipkin-server:
Zipkin需要配置jdk1.8才可以运行。
pom文件:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud