SpringCloud搭建微服务之Sleuth分布式请求链路跟踪

1. 概述

Spring Cloud Sleuth是Spring Cloud提供的一套完整的用于分布式系统中服务跟踪解决方案,常用于微服务项目的实时监控和快速定位错误异常
Span(跨度):链路跟踪的基本工作单元,通过一个64位的ID来唯一标识,包含摘要、时间戳事件、关键值注释和进度ID
Trace(跟踪):一系列Span组成一个树状结构,即一个Trace,通过一个64位的ID来唯一标识
Annotation(标注):用于及时记录一个事件
Zipkin用于提供链路追踪的可视化功能,其实现原理是,在服务调用的请求和响应中加入ID,表明上下游请求的关系,利用这些信息,可以可视化地分析服务调用链路和服务间的依赖关系

2. 搭建Zipkin Server

只需要从官网下载jar运行即可,浏览器地址栏输入https://zipkin.io/pages/quickstart
zipkin下载
下载后,直接使用命令java -jar运行jia包即可
运行zipkin
在浏览器输入地址http://localhost:9411/zipkin/
zipkin控制台

3. 搭建服务提供者

3.1. 引入核心依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

spring-cloud-starter-zipkin依赖包中已经包含了spring-cloud-starter-sleuth

3.2. 编写application.yml文件

server:
  port: 8841
spring:
  zipkin:
    enabled: true
    base-url: http://localhost:9411
  sleuth:
    sampler:
      probability: 0 #采样率0~1;1表示全部采集
eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 30 #心跳间隔时间
    lease-expiration-duration-in-seconds: 90 #超时剔除时间
    ip-address: ${spring.cloud.client.ip-address} #实例IP地址
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

如果需要在日志中打印出服务名称,需要将服务名称配置在bootstrap.yml文件中

spring:
  application:
    name: cloud-zipkin-provider

3.3. 编写logback-spring.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProperty scope="context" name="springAppName" source="spring.application.name"/>
    <!-- Example for logging into the build folder of your project -->
    <property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}"/>

    <!-- You can override this to have a custom pattern -->
    <property name="CONSOLE_LOG_PATTERN"
              value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(%X{traceId:-}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

    <!-- Appender to log to console -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <!-- Minimum logging level to be presented in the console logs-->
            <level>DEBUG</level>
        </filter>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- Appender to log to file -->
    <appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
            <maxHistory>7</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="console"/>
        <!--<appender-ref ref="flatfile"/>-->
    </root>
</configuration>

4. 搭建服务消费者

4.1. 引入核心依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

4.2. 编写application.yml文件

server:
  port: 8842
spring:
  zipkin:
    enabled: true
    base-url: http://localhost:9411
  sleuth:
    sampler:
      probability: 1
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:8761/eureka

同样也需要在bootstrap.yml文件中配置服务名称

spring:
  application:
    name: cloud-zipkin-consumer

日志文件logback-spring.xml内容见上面生产类

4.3. 编写配置类

@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

4.4. 编写controller类

@RestController
@RequestMapping("/zipkin")
public class ZipkinController {

    private static final Logger logger = LoggerFactory.getLogger(ZipkinController.class);

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getConsumerInfo")
    public String getZipkinConsumerInfo() {
        String result = restTemplate.getForObject("http://cloud-zipkin-provider/zipkin/getProviderInfo", String.class);
        logger.info("This is zipkin consumer info... The provider info is {}", result);
        return "Hello, This is zipkin consumer info, The provider info is " + result;
    }
}

5. 验证

异常启动Eureka Server、zipkin-provider和zipkin-consumer三个微服务,浏览器地址栏输入http://localhost:8842/zipkin/getConsumerInfo访问消费者接口,查看zipkin控制台
服务追踪查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值