在上一篇文章【ApiBoot Logging使用SpringCloud Openfeign透传链路信息】中咱们详细的讲解了ApiBoot Logging
整合SpringCloud
经过Openfeign
进行透传链路信息,包括traceId
(链路编号)、parentSpanId
(上级单元编号)等信息。ApiBoot Logging
不单单可使用Openfeign
传递链路信息,还支持RestTemplate
方式,本篇文章来详细的讲解下具体的使用方式。html
博客原文地址:http://blog.yuqiyu.com/apiboot-logging-using-resttemplate-transparent-traceid.htmljava
咱们须要搭建Logging Admin
服务,用于接收业务服务
上报的请求日志信息,请参考【将ApiBoot Logging采集的日志上报到Admin】文章内容.git
因为本章采用是Maven 多模块
的方式构建源码,因此咱们只须要将ApiBoot
统一版本的依赖配置在root
项目的pom.xml
内,以下所示:web
<properties> <java.version>1.8</java.version> <!--ApiBoot版本号--> <api.boot.version>2.1.5.RELEASE</api.boot.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.minbox.framework</groupId> <artifactId>api-boot-dependencies</artifactId> <version>${api.boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
接下来咱们营造本篇文章的模拟场景
,查询用户基本信息时一并查询出用户的帐号余额。spring
建立一个名为account-service
的SpringBoot
项目。json
在项目pom.xml
配置文件内添加相关依赖,以下所示:api
<dependencies> <!--SpringBoot Web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--ApiBoot Logging--> <dependency> <groupId>org.minbox.framework</groupId> <artifactId>api-boot-starter-logging</artifactId> </dependency> </dependencies>
在application.yml
配置文件内添加请求日志上报的Logging Admin
地址,以下所示:bash
spring: application: name: account-service server: port: 9090 api: boot: logging: # 控制台打印请求日志 show-console-log: true # 美化请求日志 format-console-log-json: true # Logging Admin地址 admin: server-address: 127.0.0.1:8081
注意:server-address
配置参数不须要添加http://
前缀
添加完成依赖后咱们经过@EnableLoggingClient
注解来启用ApiBoot Logging
,在AccountServiceApplication
类上添加以下所示:架构
/** * 帐户服务 * * @author 恒宇少年 */ @SpringBootApplication @EnableLoggingClient public class AccountServiceApplication { /** * logger instance */ static Logger logger = LoggerFactory.getLogger(AccountServiceApplication.class); public static void main(String[] args) { SpringApplication.run(AccountServiceApplication.class, args); logger.info("{}服务启动成功.", "帐户"); } }
@EnableLoggingClient
注解就实例化部分ApiBoot Logging
内部所须要的类,将实例放置到Spring IOC
容器内。
咱们建立一个名为AccountController
的控制器来提供查询帐户的余额信息,代码实现以下所示:app
/** * 帐户服务实现 * * @author 恒宇少年 */ @RestController @RequestMapping(value = "/account") public class AccountController { /** * 示例,内存帐户列表 */ static final HashMap<Integer, Double> ACCOUNTS = new HashMap() {{ put(1, 1233.22); put(2, 69269.22); }}; /** * 获取指定帐户的余额 * * @param accountId * @return */ @GetMapping(value = "/{accountId}") public Double getBalance(@PathVariable("accountId") Integer accountId) { return ACCOUNTS.get(accountId); } }
至此咱们的帐户服务已经编写完成,下面咱们来编写
用户服务
。
咱们来建立一个名为user-service
的SpringBoot
项目。
在项目pom.xml
配置文件内添加相关依赖,以下所示:
<dependencies> <!--SpringBoot Web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--ApiBoot Logging--> <dependency> <groupId>org.minbox.framework</groupId> <artifactId>api-boot-starter-logging</artifactId> </dependency> </dependencies>
本章咱们使用指定Logging Admin
地址的方式配置,修改application.yml
配置文件以下所示:
spring: application: name: user-service server: port: 9091 api: boot: logging: # 控制台打印请求日志 show-console-log: true # 美化请求日志 format-console-log-json: true # Logging Admin地址 admin: server-address: 127.0.0.1:8081
添加完依赖后咱们须要在XxxApplication
入口类上添加@EnableLoggingClient
注解来启用ApiBoot Logging
,以下所示:
/** * 用户服务 * * @author 恒宇少年 */ @SpringBootApplication @EnableLoggingClient public class UserServiceApplication { /** * logger instance */ static Logger logger = LoggerFactory.getLogger(UserServiceApplication.class); public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); logger.info("{}服务启动成功.", "用户"); } }
在user-service
须要访问帐户服务
获取当前用户的余额,因此咱们须要在user-service
内实例化RestTemplate
,这样咱们才能够经过RestTemplate
访问获取用户帐户余额信息,咱们直接在UserServiceApplication
类内添加实例,以下所示:
/** * 实例化RestTemplate * * @return {@link RestTemplate} */ @Bean @ConditionalOnMissingBean public RestTemplate restTemplate() { return new RestTemplate(); }
注解解释:
@ConditionalOnMissingBean
:这是SpringBoot
条件注入其中的一个注解,表示当IOC
容器内不存在RestTemplate
类型的实例时才会去执行restTemplate()
方法建立对象。/** * 用户基本信息控制器 * * @author 恒宇少年 */ @RestController @RequestMapping(value = "/user") public class UserController { /** * 示例,用户列表 */ static final HashMap<Integer, User> USERS = new HashMap() {{ put(1, new User(1, "恒宇少年")); put(2, new User(2, "于起宇")); }}; /** * 注入RestTemplate */ @Autowired private RestTemplate restTemplate; /** * 获取用户基本信息 * * @param userId 用户编号 * @return */ @GetMapping(value = "/{userId}") public User getUserInfo(@PathVariable("userId") Integer userId) { ResponseEntity<Double> responseEntity = restTemplate.getForEntity("http://localhost:9090/account/{accountId}", Double.class, userId); Double balance = responseEntity.getBody(); User user = USERS.get(userId); if (ObjectUtils.isEmpty(user)) { throw new RuntimeException("用户:" + userId + ",不存在."); } user.setBalance(balance); return user; } @Data public static class User { private Integer id; private String name; private Double balance; public User(Integer id, String name) { this.id = id; this.name = name; } } }
咱们所须要的两个服务都已经编写完成,下面咱们来测试RestTemplate
是能够透传ApiBoot Logging
的链路信息?
依次启动logging-admin
> user-service
> account-service
。
咱们使用curl
命令访问user-service
提供的地址/user
,以下所示:
➜ ~ curl http://localhost:9091/user/1 {"id":1,"name":"恒宇少年","balance":1233.22}
下面我看来看下logging-admin
控制台接收到的请求日志。
接收user-service请求日志
Receiving Service: 【user-service -> 127.0.0.1】, Request Log Report,Logging Content:[ { "endTime":1573032865311, "httpStatus":200, "requestBody":"", "requestHeaders":{ "host":"localhost:9091", "user-agent":"curl/7.64.1", "accept":"*/*" }, "requestIp":"0:0:0:0:0:0:0:1", "requestMethod":"GET", "requestParam":"{}", "requestUri":"/user/1", "responseBody":"{\"id\":1,\"name\":\"恒宇少年\",\"balance\":1233.22}", "responseHeaders":{}, "serviceId":"user-service", "serviceIp":"127.0.0.1", "servicePort":"9091", "spanId":"f8cff018-42d5-481f-98df-c19b7196b3c3", "startTime":1573032865130, "timeConsuming":181, "traceId":"16ad1dd4-beaa-4110-b4b7-fc7d952d9a57" } ]
接收account-service请求日志
Receiving Service: 【account-service -> 127.0.0.1】, Request Log Report,Logging Content:[ { "endTime":1573032865309, "httpStatus":200, "parentSpanId":"f8cff018-42d5-481f-98df-c19b7196b3c3", "requestBody":"", "requestHeaders":{ "minbox-logging-x-parent-span-id":"f8cff018-42d5-481f-98df-c19b7196b3c3", "minbox-logging-x-trace-id":"16ad1dd4-beaa-4110-b4b7-fc7d952d9a57", "host":"localhost:9090", "connection":"keep-alive", "accept":"application/json, application/*+json", "user-agent":"Java/1.8.0_211" }, "requestIp":"127.0.0.1", "requestMethod":"GET", "requestParam":"{}", "requestUri":"/account/1", "responseBody":"1233.22", "responseHeaders":{}, "serviceId":"account-service", "serviceIp":"127.0.0.1", "servicePort":"9090", "spanId":"63b18b40-5718-431c-972f-78956ce78380", "startTime":1573032865307, "timeConsuming":2, "traceId":"16ad1dd4-beaa-4110-b4b7-fc7d952d9a57" } ]
user-service
服务内的/user
路径时,由于是第一次访问ApiBoot Logging
会主动建立traceId
(链路编号)、spanId
(单元编号),由于没有上级单元
因此parentSpanId
为null
.而经过查看account-service
服务上报的请求日志时,能够看到ApiBoot Logging
相关的链路信息是经过HttpHeader
的方式进行传递的
minbox-logging-x-trace-id
-> 链路编号
minbox-logging-x-parent-span-id
-> 上级单元编号
ApiBoot Logging
在内部自动化实现了RestTemplate
的拦截器配置,因此咱们只须要建立实例就能够,而不须要主动去配置拦截器信息,具体源码请访问org.minbox.framework.logging.client.http.rest.LoggingRestTemplateInterceptor
查看。
无论你一次请求跨度几个服务,均可以将请求入口
生成的链路信息
进行依次传递,而上下级关系则是根据parentSpanId
、spanId
进行绑定的。
若是您喜欢本篇文章请为源码仓库点个Star
,谢谢!!!
本篇文章示例源码能够经过如下途径获取,目录为SpringBoot2.x/apiboot-logging-using-resttemplate-transparent-traceid
:
做者我的 博客
使用开源框架 ApiBoot 助你成为Api接口服务架构师