我有一个运行代码,带有 spring boot 和 spring cloud,使用 sleuth 来记录 TraceId。但是我在 integrationTest 中从另一个控制器调用一个控制器时遇到问题
public class TraceIdApp {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(TraceIdApp.class, args);
}
}
@Slf4j
@Getter
@RestController
public class TraceIdController {
private SpanAccessor spanAccessor;
private RestTemplate restTemplate;
private String url;
@Autowired
public TraceIdController(SpanAccessor spanAccessor, RestTemplate restTemplate,
@Value("http://localhost:${local.server.port:${server.port:8080}}/other") String url) {
this.spanAccessor = spanAccessor;
this.restTemplate = restTemplate;
this.url = url;
}
@GetMapping(path = "/")
public String handlerOne() {
long traceId = spanAccessor.getCurrentSpan().getTraceId();
log.info("loggin the real traceId => " + traceId);
String response = getRestTemplate().getForObject(getUrl(), String.class);
return "one" + response;
}
@GetMapping(path = "/other")
public String handlerOther() {
long traceId = spanAccessor.getCurrentSpan().getTraceId();
log.info("loggin the real traceId => " + traceId);
return "other";
}
}
@Getter
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class TraceIdAppTest {
@Autowired
private SpanAccessor spanAccessor;
@Autowired
private MockMvc mockMvc;
@Value("http://localhost:${local.server.port:${server.port:8080}}/other")
String url;
@Test
public void test() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk());
assertTrue("trace is wrong type", getSpanAccessor() instanceof DefaultTracer);
}
}
第一次在测试中运行,我注意到 url 上的端口在测试中采用了正确的值,但是它在控制器上的值为零。硬编码端口并没有解决问题。