Zipkin with Spring Boot Example

Here’s a basic example of how you might instrument a simple web service with Zipkin in Java using Spring Boot and Sleuth:

Add Dependencies:

pom.xml

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-sleuth</artifactId>

</dependency>

<dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-sleuth-zipkin</artifactId>

</dependency>

Configuration

spring:

  zipkin:

    base-url: http://localhost:9411

  sleuth:

    sampler:

      probability: 1.0


Creating Spans:

// inject tracer dependency

@Autowired
private Tracer tracer;

public void someMethod() {

    // get the next span

    Span newSpan = tracer.nextSpan().name("someMethod").start();

    // try with resource statement:: must implement autocloseable
    //start method will start the span

    try (Tracer.SpanInScope ws = tracer.withSpan(newSpan.start())) {

        // Business logic here

    } finally {

        newSpan.finish();

    }
}

Propagating Context:

Spring Cloud Sleuth automatically propagates the tracing context for you 

when using RestTemplate or Feign clients.


Comments

Popular posts from this blog

Hibernate Many to Many Relationship

Why Integral Calculus limit tending to infinity a sacrilege

Introduction