Add integration sample and vanilla non-zipkin sample

This commit is contained in:
Dave Syer
2015-08-12 13:59:42 +01:00
parent 405e07f74a
commit 673d8cb0b8
22 changed files with 691 additions and 62 deletions

View File

@@ -28,7 +28,7 @@
<modules>
<module>spring-cloud-sleuth-core</module>
<module>spring-cloud-sleuth-zipkin</module>
<module>spring-cloud-sleuth-sample</module>
<module>spring-cloud-sleuth-samples</module>
<module>docs</module>
</modules>

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.instrument.integration;
import static org.springframework.cloud.sleuth.Trace.PARENT_ID_NAME;
import static org.springframework.cloud.sleuth.Trace.PROCESS_ID_NAME;
import static org.springframework.cloud.sleuth.Trace.SPAN_ID_NAME;
import static org.springframework.cloud.sleuth.Trace.SPAN_NAME_NAME;
import static org.springframework.cloud.sleuth.Trace.TRACE_ID_NAME;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.cloud.sleuth.Span;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
/**
* @author Dave Syer
*
*/
public class SpanMessageHeaders {
public static Message<?> addSpanHeaders(Message<?> message, Span span) {
if (span==null) {
return message;
}
Map<String, String> headers = new HashMap<String, String>();
addHeader(headers, TRACE_ID_NAME, span.getTraceId());
addHeader(headers, SPAN_ID_NAME, span.getSpanId());
addHeader(headers, PARENT_ID_NAME, getFirst(span.getParents()));
addHeader(headers, SPAN_NAME_NAME, span.getName());
addHeader(headers, PROCESS_ID_NAME, span.getProcessId());
return MessageBuilder.fromMessage(message).copyHeaders(headers).build();
}
private static void addHeader(Map<String, String> headers, String name, String value) {
if (value!=null) {
headers.put(name, value);
}
}
private static String getFirst(List<String> parents) {
return parents==null || parents.isEmpty() ? null : parents.get(0);
}
}

View File

@@ -23,18 +23,12 @@ import static org.springframework.cloud.sleuth.Trace.SPAN_NAME_NAME;
import static org.springframework.cloud.sleuth.Trace.TRACE_ID_NAME;
import static org.springframework.util.StringUtils.hasText;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.cloud.sleuth.MilliSpan;
import org.springframework.cloud.sleuth.MilliSpan.MilliSpanBuilder;
import org.springframework.cloud.sleuth.NullScope;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.TraceContextHolder;
import org.springframework.cloud.sleuth.TraceScope;
import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
@@ -54,7 +48,7 @@ public class TraceChannelInterceptor extends ChannelInterceptorAdapter {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
if (TraceContextHolder.isTracing()) {
return message;
return SpanMessageHeaders.addSpanHeaders(message, TraceContextHolder.getCurrentSpan());
}
String spanId = getHeader(message, SPAN_ID_NAME);
String traceId = getHeader(message, TRACE_ID_NAME);
@@ -67,9 +61,9 @@ public class TraceChannelInterceptor extends ChannelInterceptorAdapter {
MilliSpanBuilder span = MilliSpan.builder().traceId(traceId).spanId(spanId);
String parentId = getHeader(message, PARENT_ID_NAME);
String processId = getHeader(message, PROCESS_ID_NAME);
String parentName = getHeader(message, SPAN_NAME_NAME);
if (parentName != null) {
span.name(parentName);
String spanName = getHeader(message, SPAN_NAME_NAME);
if (spanName != null) {
span.name(spanName);
}
if (processId != null) {
span.processId(processId);
@@ -85,27 +79,7 @@ public class TraceChannelInterceptor extends ChannelInterceptorAdapter {
else {
traceScope = this.trace.startSpan(name);
}
if (traceScope == NullScope.INSTANCE) {
return message;
} else {
Map<String, String> headers = new HashMap<String, String>();
addHeader(headers, TRACE_ID_NAME, traceScope.getSpan().getTraceId());
addHeader(headers, SPAN_ID_NAME, traceScope.getSpan().getSpanId());
addHeader(headers, PARENT_ID_NAME, getFirst(traceScope.getSpan().getParents()));
addHeader(headers, SPAN_NAME_NAME, traceScope.getSpan().getName());
addHeader(headers, PROCESS_ID_NAME, traceScope.getSpan().getProcessId());
return MessageBuilder.fromMessage(message).copyHeaders(headers).build();
}
}
private void addHeader(Map<String, String> headers, String name, String value) {
if (value!=null) {
headers.put(name, value);
}
}
private String getFirst(List<String> parents) {
return parents==null || parents.isEmpty() ? null : parents.get(0);
return SpanMessageHeaders.addSpanHeaders(message, traceScope.getSpan());
}
private String getHeader(Message<?> message, String name) {

View File

@@ -174,7 +174,7 @@ implements ExecutorChannelInterceptor {
@Override
public String toString() {
return "MessageWithThreadState{" + "message=" + this.message + ", span="
return "MessageWithSpan{" + "message=" + this.message + ", span="
+ this.span + ", messageHeaders=" + this.messageHeaders + '}';
}

View File

@@ -21,26 +21,26 @@ import static org.springframework.cloud.sleuth.Trace.SPAN_ID_NAME;
import static org.springframework.cloud.sleuth.Trace.TRACE_ID_NAME;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.test.ImportAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.TraceContextHolder;
import org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration;
import org.springframework.cloud.sleuth.TraceScope;
import org.springframework.cloud.sleuth.instrument.integration.TraceChannelInterceptorTests.App;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -51,43 +51,66 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringApplicationConfiguration(classes=App.class)
@IntegrationTest
@DirtiesContext
public class TraceChannelInterceptorTests {
public class TraceChannelInterceptorTests implements MessageHandler {
@Autowired
@Qualifier("channel")
private PollableChannel channel;
private DirectChannel channel;
@Autowired
private Trace trace;
private Message<?> message;
@Override
public void handleMessage(Message<?> message) throws MessagingException {
this.message = message;
}
@Before
public void init() {
this.channel.subscribe(this);
}
@After
public void close() {
TraceContextHolder.setCurrentSpan(null);
this.channel.unsubscribe(this);
}
@Test
public void testSpanCreation() {
this.channel.send(MessageBuilder.withPayload("hi").build());
assertNotNull("message was null", this.message);
Message<?> message = this.channel.receive(0);
assertNotNull("message was null", message);
String spanId = message.getHeaders().get(SPAN_ID_NAME, String.class);
String spanId = this.message.getHeaders().get(SPAN_ID_NAME, String.class);
assertNotNull("spanId was null", spanId);
String traceId = message.getHeaders().get(TRACE_ID_NAME, String.class);
String traceId = this.message.getHeaders().get(TRACE_ID_NAME, String.class);
assertNotNull("traceId was null", traceId);
}
@Test
public void testHeaderCreation() {
TraceScope traceScope = this.trace.startSpan("testSendMessage", new AlwaysSampler(), null);
this.channel.send(MessageBuilder.withPayload("hi").build());
traceScope.close();
assertNotNull("message was null", this.message);
String spanId = this.message.getHeaders().get(SPAN_ID_NAME, String.class);
assertNotNull("spanId was null", spanId);
String traceId = this.message.getHeaders().get(TRACE_ID_NAME, String.class);
assertNotNull("traceId was null", traceId);
}
@Configuration
@EnableAutoConfiguration
@MessageEndpoint
@EnableIntegration
@ImportAutoConfiguration({TraceSpringIntegrationAutoConfiguration.class, TraceAutoConfiguration.class})
static class App {
@Bean
public QueueChannel channel() {
return new QueueChannel();
public DirectChannel channel() {
return new DirectChannel();
}
@Bean

View File

@@ -36,9 +36,7 @@ import org.springframework.cloud.sleuth.instrument.integration.TraceContextPropa
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.PollableChannel;
@@ -87,8 +85,6 @@ public class TraceContextPropagationChannelInterceptorTests {
@Configuration
@EnableAutoConfiguration
@MessageEndpoint
@EnableIntegration
static class App {
@Bean

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-sleuth-samples</artifactId>
<packaging>pom</packaging>
<name>Spring Cloud Sleuth Samples</name>
<description>Spring Cloud Sleuth Samples</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
</parent>
<modules>
<module>spring-cloud-sleuth-sample</module>
<module>spring-cloud-sleuth-sample-messaging</module>
<module>spring-cloud-sleuth-sample-zipkin</module>
</modules>
</project>

View File

@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-sleuth-sample-messaging</artifactId>
<packaging>jar</packaging>
<name>spring-cloud-sleuth-sample-messaging</name>
<description>Spring Cloud Sleuth Sample</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!--skip deploy -->
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
/**
* @author Dave Syer
*
*/
@MessagingGateway
public interface SampleGateway {
@Gateway(requestChannel="messages")
void send(String message);
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.sleuth.Sampler;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.kristofa.brave.LoggingSpanCollectorImpl;
import com.github.kristofa.brave.SpanCollector;
/**
* @author Spencer Gibb
*/
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableAsync
@IntegrationComponentScan
@RestController
public class SampleMessagingApplication {
@Autowired
private SampleGateway gateway;
@Bean
public Sampler<?> defaultSampler() {
return new AlwaysSampler();
}
@RequestMapping("/")
public String home() {
String msg = "Hello";
this.gateway.send(msg);
return msg;
}
public static void main(String[] args) {
SpringApplication.run(SampleMessagingApplication.class, args);
}
// Use this for debugging (or if there is no Zipkin collector running on port 9410)
@Bean
@ConditionalOnProperty("span.logging.enabled")
public SpanCollector spanCollector() {
return new LoggingSpanCollectorImpl();
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
/**
* @author Dave Syer
*
*/
@MessageEndpoint
@Slf4j
public class SampleService {
@ServiceActivator(inputChannel="messages")
public void log(Message<?> message) {
log.info("Received: " + message);
}
}

View File

@@ -0,0 +1,18 @@
server:
port: 3381
spring:
application:
name: testSleuthApp
sleuth:
log:
json:
enabled: true
logging:
pattern:
console: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex'
span:
logging:
enabled: true

View File

@@ -4,9 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-sleuth-sample</artifactId>
<artifactId>spring-cloud-sleuth-sample-zipkin</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Sleuth Sample</name>
<name>spring-cloud-sleuth-sample-zipkin</name>
<description>Spring Cloud Sleuth Sample</description>
<parent>

View File

@@ -34,7 +34,7 @@ import com.github.kristofa.brave.SpanCollector;
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableAsync
public class SampleApplication {
public class SampleZipkinApplication {
public static final String CLIENT_NAME = "testApp";
@@ -49,12 +49,12 @@ public class SampleApplication {
}
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
SpringApplication.run(SampleZipkinApplication.class, args);
}
// Use this for debugging (or if there is no Zipkin collector running on port 9410)
@Bean
@ConditionalOnProperty("sleuth.sample.logging.collector.enabled")
@ConditionalOnProperty("span.logging.enabled")
public SpanCollector spanCollector() {
return new LoggingSpanCollectorImpl();
}

View File

@@ -9,6 +9,10 @@ logging:
pattern:
console: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex'
span:
logging:
enabled: true
endpoints:
health:
sensitive: false

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-sleuth-sample</artifactId>
<packaging>jar</packaging>
<name>Spring Cloud Sleuth Sample</name>
<description>Spring Cloud Sleuth Sample</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!--skip deploy -->
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import java.util.Random;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author Spencer Gibb
*/
@Component
public class SampleBackground {
@Autowired
private Trace trace;
@SneakyThrows
@Async
public void background() {
final Random random = new Random();
int millis = random.nextInt(1000);
Thread.sleep(millis);
this.trace.addKVAnnotation("background-sleep-millis", String.valueOf(millis));
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import java.util.Random;
import java.util.concurrent.Callable;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.TraceContextHolder;
import org.springframework.cloud.sleuth.TraceScope;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.context.ApplicationListener;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author Spencer Gibb
*/
@Slf4j
@RestController
public class SampleController implements
ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Autowired
private RestTemplate restTemplate;
@Autowired
private Trace trace;
@Autowired
private SampleBackground controller;
private int port;
@SneakyThrows
@RequestMapping("/")
public String hi() {
final Random random = new Random();
Thread.sleep(random.nextInt(1000));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/hi2", String.class);
return "hi/" + s;
}
@RequestMapping("/call")
public Callable<String> call() {
return new Callable<String>() {
@Override
public String call() throws Exception {
final Random random = new Random();
int millis = random.nextInt(1000);
Thread.sleep(millis);
SampleController.this.trace.addKVAnnotation("callable-sleep-millis", String.valueOf(millis));
Span currentSpan = TraceContextHolder.getCurrentSpan();
return "async hi: " + currentSpan;
}
};
}
@RequestMapping("/async")
public String async() {
this.controller.background();
return "ho";
}
@SneakyThrows
@RequestMapping("/hi2")
public String hi2() {
final Random random = new Random();
int millis = random.nextInt(1000);
Thread.sleep(millis);
this.trace.addKVAnnotation("random-sleep-millis", String.valueOf(millis));
return "hi2";
}
@SneakyThrows
@RequestMapping("/traced")
public String traced() {
TraceScope scope = this.trace.startSpan("customTraceEndpoint",
new AlwaysSampler(), null);
final Random random = new Random();
int millis = random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.trace.addKVAnnotation("random-sleep-millis", String.valueOf(millis));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/call", String.class);
scope.close();
return "traced/" + s;
}
@SneakyThrows
@RequestMapping("/start")
public String start() {
final Random random = new Random();
int millis = random.nextInt(1000);
log.info("Sleeping for {} millis", millis);
Thread.sleep(millis);
this.trace.addKVAnnotation("random-sleep-millis", String.valueOf(millis));
String s = this.restTemplate.getForObject("http://localhost:" + this.port
+ "/call", String.class);
return "start/" + s;
}
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.sleuth.Sampler;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* @author Spencer Gibb
*/
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableAsync
public class SampleSleuthApplication {
public static final String CLIENT_NAME = "testApp";
@Bean
public Sampler<?> defaultSampler() {
return new AlwaysSampler();
}
@Bean
public SampleController sampleController() {
return new SampleController();
}
public static void main(String[] args) {
SpringApplication.run(SampleSleuthApplication.class, args);
}
}

View File

@@ -0,0 +1,22 @@
server:
port: 3379
spring:
application:
name: testSleuthApp
sleuth:
log:
json:
enabled: true
logging:
pattern:
console: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID:- }){magenta} %clr(---){faint} %clr([trace=%X{X-Trace-Id:-},span=%X{X-Span-Id:-}]){yellow} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex'
endpoints:
health:
sensitive: false
restart:
enabled: true
shutdown:
enabled: true