RestTemplate instrumentation

Updated at:

This topic uses a demo project to demonstrate how to use SOFATracer for RestTemplate instrumentation.

Click here to download the demo project for this topic.

If you have a simple Spring Web project built on SOFABoot, follow these steps:

  1. Import dependencies

  2. Project configuration

  3. Add a controller that provides a RESTful service

  4. Obtain RestTemplate

  5. Start the application

  6. View logs

Import dependencies

In your SOFABoot Web project, import the following Tracer dependency:

<dependency>
    <groupId>com.alipay.sofa</groupId>
    <artifactId>tracer-enterprise-sofa-boot-starter</artifactId>
</dependency>

After you add the Tracer starter dependency, you can add configuration items in the SOFABoot global configuration file to customize the behavior of Tracer. For more information, see Tracer configuration items.

Project configuration

In the project's application.properties file, add the parameters used by SOFATracer, such as spring.application.name and logging.path.

  • spring.application.name specifies the name of the current application.

  • logging.path specifies the output directory for logs.

# Application Name
spring.application.name=TestTemplateDemo
# Logging path
logging.path=./logs

Add a controller that provides a RESTful service

In your project code, add a simple controller. For example:

    @RestController
    public class SampleController{
        private final AtomicLong counter =new AtomicLong(0);
        @RequestMapping("/rest")
        public Map<String,Object> rest(){
            Map<String,Object> map =new HashMap<String,Object>();
            map.put("count", counter.incrementAndGet());
            return map;
        }

        @RequestMapping("/asyncrest")
        public Map<String,Object> asyncrest() throws InterruptedException{
            Map<String,Object> map =new HashMap<String,Object>();
            map.put("count", counter.incrementAndGet());
            Thread.sleep(5000);
            return map;
        }
    }

Construct RestTemplate

Construct RestTemplate instances to call the RESTful service:

  • Construct a RestTemplate instance for synchronous calls

    RestTemplate restTemplate =SofaTracerRestTemplateBuilder.buildRestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(
    "http://sac.alipay.net:8080/rest",String.class);
  • Construct a RestTemplate instance for asynchronous calls

    AsyncRestTemplate asyncRestTemplate =SofaTracerRestTemplateBuilder
    .buildAsyncRestTemplate();
    ListenableFuture<ResponseEntity<String>> forEntity = asyncRestTemplate.getForEntity(
    "http://sac.alipay.net:8080/asyncrest",String.class);

Get RestTemplate

Obtain the RestTemplate instance using automatic injection:

@Autowired
RestTemplate             restTemplate;

Start the application

Start the SOFABoot application. You will see startup logs in the console:

2018-10-2410:45:28.683  INFO 5081---[           main] o.s.j.e.a.AnnotationMBeanExporter:Registering beans for JMX exposure on startup
2018-10-2410:45:28.733  INFO 5081---[           main] s.b.c.e.t.TomcatEmbeddedServletContainer:Tomcat started on port(s):8080(http)
2018-10-2410:45:28.736  INFO 5081---[           main] c.a.s.t.e.r.RestTemplateDemoApplication:StartedRestTemplateDemoApplication in 2.163 seconds (JVM running for 3.603)

The logs for successful calls are as follows:

2018-10-2410:45:28.989  INFO 5081---[           main] c.a.s.t.e.r.RestTemplateDemoApplication:Response is {"count":1}
2018-10-2410:45:34.014  INFO 5081---[           main] c.a.s.t.e.r.RestTemplateDemoApplication:AsyncResponse is {"count":2}
2018-10-2410:45:34.014  INFO 5081---[           main] c.a.s.t.e.r.RestTemplateDemoApplication: test finish .......

View logs

In the application.properties file, the log output directory is set to ./logs. This path points to the root directory of the current application. You can change this directory as needed. In the project's root directory, you can find log files with a structure similar to the following:

./logs
├── spring.log
└── tracelog
├── resttemplate-digest.log
├── resttemplate-stat.log
├── spring-mvc-digest.log
├── spring-mvc-stat.log
├──static-info.log
└── tracer-self.log

The demo project constructs two RestTemplate instances, one for synchronous calls and one for asynchronous calls, to invoke the same RESTful service. After the calls are complete, you can see logs similar to the following in resttemplate-digest.log:

  • Summary logs

    {"time":"2019-09-03 10:33:10.336","local.app":"RestTemplateDemo","traceId":"0a0fe9271567477985327100211176","spanId":"0","span.kind":"client","result.code":"200","current.thread.name":"SimpleAsyncTaskExecutor-1","time.cost.milliseconds":"5009ms","request.url":"http://localhost:8801/asyncrest","method":"GET","req.size.bytes":0,"resp.size.bytes":0,"sys.baggage":"","biz.baggage":""}
  • Statistics logs

    {"time":"2019-09-03 10:34:04.130","stat.key":{"method":"GET","local.app":"RestTemplateDemo","request.url":"http://localhost:8801/asyncrest"},"count":1,"total.cost.milliseconds":5009,"success":"true","load.test":"F"}