java Spring Cloud sleuth中每个新的http请求都有不同的traceId

vs3odd8k  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(147)

最近,我开始使用spring cloud sleuth来跟踪应用程序中的请求,我编写了示例项目来测试此功能,但当应用程序运行时,日志显示每个新的http请求都有不同的跟踪id。
下面是May代码:Config.java

package com.cloud;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan()
@EnableAutoConfiguration()
@EnableWebMvc
public class Config {
}

Controller.java

package com.cloud;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.SpanAccessor;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class Controller {

@Autowired
SpanAccessor spanAccessor;
@Autowired
RestTemplate restTemplate;
int port = 8080;
private static final Logger LOGGER = LoggerFactory.getLogger(Controller.class);

@RequestMapping("/")
public String hi() throws InterruptedException {
    LOGGER.debug("you called hi");
    debug();
    String s = this.restTemplate
            .getForObject("http://localhost:" + this.port + "/cloud/hi2", String.class);
    return "hi/" + s;
}

@RequestMapping("/hi2")
public String hi2() throws InterruptedException {
    LOGGER.debug("you called hi2");
    debug();
    return "welcome";
}

public void debug(){
    Span span = spanAccessor.getCurrentSpan();
    LOGGER.info("span id is "+span.getSpanId()+" and trace id is "+span.getTraceId());
}

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

这里是log:

you called hi: span id is 6716502497271349964 and trace id is 6716502497271349964
you called hi2: span id is -4542377791493777157  and trace id is -4542377791493777157
5fjcxozz

5fjcxozz1#

我复制/粘贴你的代码,它的工作原理,但我应该提到一些区别:
首先,也是最重要的,我用一个主要的女巫和springboot anotation来运行它:

@SpringBootApplication(scanBasePackages="com.cloud")

第二,我删除了你的Config类,因为它什么都不做。
第三,我的Spring版本是1.5.1.RELEASE,Spring云版本是Dalston.BUILD-SNAPSHOT
这是日志

2017-03-07 10:48:29.716  INFO [traceId,2488a4c8d3f7238a,2488a4c8d3f7238a,false] 4179 --- [nio-8080-exec-1] com.cloud.Controller                     : span id is 2632535164654658442 and trace id is 2632535164654658442
2017-03-07 10:48:45.162  INFO [traceId,2488a4c8d3f7238a,f5e476485b30fd85,false] 4179 --- [nio-8080-exec-2] com.cloud.Controller                     : span id is -728327186587517563 and trace id is 2632535164654658442

相关问题