0

最近开始用spring cloud sleuth跟踪应用中的请求,写了样例项目来测试这个特性,但是应用运行时,日志显示每一个新的http请求都有不同的trace id。

这是可能的代码: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 {
}

控制器.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();
}
}

这是日志:

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

1 回答 1

1

我复制/粘贴你的代码,它可以工作,但我应该提到一些不同之处:

首先也是最重要的,我用一个主要的女巫来运行它,当然还有 springboot 注释:

@SpringBootApplication(scanBasePackages="com.cloud")

其次,我删除了您的 Config 类,因为它没有做任何事情。

第三,mi spring 版本是 1.5.1.RELEASE,spring cloud 版本是 Dalston.BUILD-SNAPSHOT

这是日志:

2017-03-07 10:48:29.716信息[TraceID,2488A4C8D3F7238A,2488A4C8D3F7238A,FALSE] 4179 --- [NIO-8080-EXEC-1] 03-07 10:48:45.162 INFO [traceId,2488a4c8d3f7238a,f5e476485b30fd85,false] 4179 --- [nio-8080-exec-2] com.cloud.Controller:span id 为 -728327186587517563,trace id 为 2632445356

于 2017-03-07T09:56:10.310 回答