随着业务的发展,系统规模愈来愈大,各微服务直接的调用关系也变得愈来愈复杂。一般一个由客户端发起的请求在后端系统中会通过多个不一样的微服务调用协同产生最后的请求结果,几乎每个前端请求都会造成一条复杂的分布式服务调用链路,对每一个请求实现全链路跟踪,能够帮助咱们快速发现错误根源以及监控分析每条请求链路上性能瓶颈。
针对分布式服务跟踪,Spring Cloud Sleuth提供了一套完整的解决方案。html
参考《SpringCloud微服务实战》第11章。
先查看跟踪日志了解每项的含义前端
2019-02-27 20:40:56.419 INFO [service-a,e79b41414a56743d,e79b41414a56743d,true] 8276 --- [nio-9001-exec-5] cn.sp.controller.ServiceController : ==<Call Service-a>==
这个以前的文章有,故省略java
1.建立项目引入依赖git
其实spring-cloud-starter-zipkin中已经有了sleuth的依赖,spring-cloud-starter-sleuth能够省略。
2. 启动类github
@EnableEurekaClient
@SpringBootApplication
public class ServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
@RestController
public class ServiceController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplate restTemplate;
@GetMapping("/service-a")
public String test(){
logger.info("==<Call Service-a>==");
return restTemplate.getForEntity("http://service-b/test",String.class).getBody();
}
}
这里的url(http://service-b/test)用的是服务名当虚拟域名而不是ip+端口号的形式,至于为何能够访问能够查看这篇文章【Spring Cloud中restTemplate是如何经过服务名主求到具体服务的】。web
4.配置文件application.ymlspring
1.建立项目引入依赖pom文件同上
2.启动类添加注解 @EnableEurekaClient
3.ServiceController后端
@RestController
public class ServiceController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping("/test")
public String test(){
logger.info("==<Call Service-b>==");
return "OK";
}
}
4.配置文件application.ymlbash
2.启动类添加注解 @EnableZipkinServer
注意: 这里我排除了log4j的依赖,由于已经有了相同的类文件启动会报错。微信
2019-02-27 21:18:05.119 INFO [service-a,3e487761c9b13a2e,3e487761c9b13a2e,true] 8276 --- [nio-9001-exec-9] cn.sp.controller.ServiceController : ==<Call Service-a>==
服务B的日志以下:
2019-02-27 21:18:05.128 INFO [service-b,3e487761c9b13a2e,8d49352c6645c6f9,true] 13860 --- [nio-9002-exec-8] cn.sp.controller.ServiceController : ==<Call Service-b>==
点击查找,服务名选择service-a便可看到最近的统计数据,还能够根据条件进行筛选。
点击依赖,依赖分析就能够看到服务以前的依赖关系。
完整代码地址。
基本是根据《SpringCloud微服务实战》这本书来的,可是中间仍是踩了几个坑,好比开始报No instances available for service-b的时候我一直觉得是代码哪里出了问题,浪费了不少时间。
SpringCloudSleuth除了把请求链路数据整合到Zipkin中外,还能够保存到消息队列,ELK等,还算比较强大。可是除了HTTP请求,不知道对于GRPC这样的通讯方式是否也能实现链路跟踪。
查了下资料支持Grpc的,demo地址:https://github.com/tkvangorder/sleuth-grpc-sample
官方文档:https://cloud.spring.io/spring-cloud-sleuth/single/spring-cloud-sleuth.html#_grpc