Spring Cloud Sleuth 功能是在分布式系统中提供服务调用追踪。集成Zipkin提供了可视化界面。
1.创建SleuthZipkinServer工程添加依赖
org.springframework.boot
spring-boot-starter-web
io.zipkin.java
zipkin-server
io.zipkin.java
zipkin-autoconfigure-ui
io.zipkin.java
zipkin-ui
2.4.3
2.修改配置文件
server:
port: 8020
3.启动类加入注解
@EnableZipkinServer
4.创建2个相互调用的工程
4.1 创建SleuthZipkina工程并添加依赖
org.springframework.cloud
spring-cloud-starter-zipkin
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-starter-sleuth
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-sleuth-core
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-sleuth-zipkin
1.3.1.RELEASE
org.aspectj
aspectjweaver
1.8.13
4.2 修改工程a配置文件
server:
port: 8021
spring:
zipkin:
base-url: http://localhost:8020
application:
name: service-hi
4.3 工程a启动类
@SpringBootApplication
@RestController
public class SleuthzipkinaApplication {
public static void main(String[] args) {
SpringApplication.run(SleuthzipkinaApplication.class, args);
}
@Autowired
private RestTemplate restTemplate;
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@RequestMapping("/hi")
public String callHome() {
return restTemplate.getForObject("http://localhost:8022/miya", String.class);
}
@RequestMapping("/info")
public String info() {
return "i'm service-hi";
}
@Bean
public AlwaysSampler defaultSampler(){
return new AlwaysSampler();
}
}
4.4 创建SleuthZipkinb工程并添加依赖
org.springframework.cloud
spring-cloud-starter-zipkin
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-sleuth-zipkin
1.3.1.RELEASE
org.springframework.cloud
spring-cloud-starter-sleuth
1.3.1.RELEASE
4.5 修改工程b配置文件
server:
port: 8022
spring:
zipkin:
base-url: http://localhost:8020
application:
name: service-miya
4.6 工程b启动类
@SpringBootApplication
@RestController
public class SleuthzipkinbApplication {
public static void main(String[] args) {
SpringApplication.run(SleuthzipkinbApplication.class, args);
}
@RequestMapping("/hi")
public String home(){
return "hi i'm miya!";
}
@RequestMapping("/miya")
public String info(){
return restTemplate.getForObject("http://localhost:8021/info",String.class);
}
@Autowired
private RestTemplate restTemplate;
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
5.按顺序启动三个工程
访问http://localhost:8021/hi/ 页面返回i'm service-hi,表示调用成功
访问http://localhost:8020/
点列表中的请求查看详情
点Service列表显示请求信息
点依赖分析显示如下图