SkyWalking 在微服务中的使用(2)

435 阅读2分钟

该篇文章是我在掘金的第二篇原创文章,继续来跟大家来共同学习下 SkyWalking 在微服务下的一些使用方式。

第一篇关于 SkyWalking 的文章发布到现在已经一年了,期间耽搁的确实太久了,主要是因为那篇文章发了没多久就跳槽了,然后新公司比较忙,就耽搁了(找个借口忽悠下你们,其实还是自己懒,不过确实新公司挺忙的,摸鱼时间都没了)废话不多说了,老规矩,直接开整!

image.png

书接上回,本篇文章主要演示一波如何在 SkyWalking 中植入 request.body 以及 response.body 这两个信息的展示,分为两步:

1、首先在 Maven 中引入 SkyWalking 工具包的依赖:

<!-- SkyWalking 工具包依赖 -->
<dependency>
    <groupId>org.apache.skywalking</groupId>
    <artifactId>apm-toolkit-trace</artifactId>
    <version>8.8.0</version>
</dependency>

2、通过继承 Http 过滤器拿到请求体及响应体

核心是通过 ActiveSpan.tag 方法打上一个 Tag 标记,这样在请求链路界面就可以看到了

@Slf4j
@Component
public class ApmHttpInfoFilter extends HttpFilter {
​
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 解决请求体只能被读取一次的问题,先缓存起来
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        // 解决响应体只能被读取一次的问题,先缓存起来
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
​
        filterChain.doFilter(requestWrapper, responseWrapper);
​
        try {
            // 请求方法
            String method = request.getMethod();
            // 请求内容类型
            String requestContentType = request.getContentType();
​
            // 请求体信息针对于 POST 和 PUT 类型
            if ((HttpMethod.POST.name().equals(method) || HttpMethod.PUT.name().equals(method)) && requestContentType.indexOf(MediaType.APPLICATION_JSON_VALUE) != -1) {
                // 获取请求体信息
                String requestBody = new String(requestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
                if (StringUtils.hasLength(requestBody)) {
                    // 往 SkyWalking 中添加 Tag 信息(核心)
                    ActiveSpan.tag("request.body", requestBody);
                }
            }
​
            // 响应内容类型
            String responseContentType = response.getContentType();
            if (responseContentType.indexOf(MediaType.APPLICATION_JSON_VALUE) != -1) {
                // 获取返回值 body 信息
                String responseBody = new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
                if (StringUtils.hasLength(responseBody)) {
                    // 往 SkyWalking 中添加 Tag 信息(核心)
                    ActiveSpan.tag("response.body", responseBody);
                }
            }
        } catch (Exception ex) {
            log.error("拦截 Http 请求添加 SkyWalking Tag 信息异常", ex);
        } finally {
            // 将响应信息写回到输出流,解决返回的响应体是空的问题
            responseWrapper.copyBodyToResponse();
        }
    }
}

完成以上两步再去请求一下,就是下图这种效果啦~

image.png 好了,以上就完成了在 SkyWalking 中植入 Tag 标记,感谢大家的观看,共同学习!共同进步!冲鸭!!