'How can we use Spring Cloud Sleuth with spring MVC project?
I am trying to use spring cloud sleuth with spring web mvc project. We are sending the request from spring web mvc to another spring boot project. I need to have the traceID and spanId to display in the UI. How can we achieve this?
EDIT
POM.xml for the spring boot application. I am using the latest version of Spring Boot and added the dependency of spring cloud sleuth.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Web MVC code: I am using spring rest template and calling the spring boot service from the spring web mvc application.
@Controller
public class HelloController {
@Autowired
RestTemplate restTemplate;
private Logger logger = Logger.getLogger(HelloController.class);
@GetMapping("/hello")
public String hello(Model model) {
logger.info("Hello from controller");
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8092/test", String.class);
String response = entity.getBody();
logger.info("Response from Service: "+ response);
model.addAttribute("name", "Test");
return "welcome";
}
}
Solution 1:[1]
In order to do that, you need to inject the Tracer bean and then if you call tracer.currentSpan().context().traceIdString() and tracer.currentSpan().context().spanIdString().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin Grzejszczak |
