原文请参考Spring Cloud构建微服务架构:分布式服务跟踪(入门)【Dalston版】和 Spring Cloud构建微服务架构:分布式服务跟踪(跟踪原理)【Dalston版】我只是在学习过程中,记录一下,加深记忆和理解。
使用Spring Cloud Sleuth来为我们的微服务架构增加分布式服务跟踪的能力。
准备工作
1.服务注册中心eureka-server
2.创建微服务trace-1:实现一个REST接口/trace-1
,调用该接口后将通过Ribbon触发对trace-2
应用的调用。
- 创建基本的spring boot应用,添加依赖起步依赖spring-cloud-starter-netflix-eureka-server和spring-cloud-starter-netflix-ribbo
- 在配置类添加注解@EnableDiscoveryClient 把微服务注册到服务注册中心
- 配置application.properties文件 :配置微服务的名称和端口,指定注册中心的地址
#指定微服务名称 使用微服务名称就可以访问微服务
spring.application.name=trace-1
#指定微服务端口
server.port=9101
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
- 在配置类中初始化RestTemplate,用来真正发起REST请求。并增加@LoadBalanced注解
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
- 实现一个REST接口
/trace-1
,调用该接口后将通过Ribbon触发对trace-2
应用的调用
package com.example.trace1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class Trace1Controller {
@Autowired
private RestTemplate restTemplate;
Logger logger = LoggerFactory.getLogger(Trace1Controller.class);
@RequestMapping(value = "/trace-1", method = RequestMethod.GET)
public String trace() {