springMVC、boot、dubbo集成zipkin做链路追踪

首先引入maven相关依赖

 <brave.version>3.16.0</brave.version>
    <zipkin.reporter.version>1.1.2</zipkin.reporter.version>
</properties>

<dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>io.zipkin.brave</groupId>
            <artifactId>brave-core</artifactId>
            <version>${brave.version}</version>
        </dependency>

        <dependency>
            <groupId>io.zipkin.brave</groupId>
            <artifactId>brave-spancollector-http</artifactId>
            <version>${brave.version}</version>
        </dependency>

        <dependency>
            <groupId>io.zipkin.brave</groupId>
            <artifactId>brave-web-☛servlet-filter</artifactId>
            <version>${brave.version}</version>
        </dependency>

        <dependency>
            <groupId>io.zipkin.brave</groupId>
            <artifactId>brave-apache-http-interceptors</artifactId>
            <version>${brave.version}</version>
        </dependency>
        <dependency>
            <groupId>io.zipkin.reporter</groupId>
            <artifactId>zipkin-sender-okhttp3</artifactId>
            <version>${zipkin.reporter.version}</version>
        </dependency>

编写mvc和boot的zipkin配置类

package com.rt.platform.infosys.infoopsys.common.web.zipkin;

import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.httpclient.BraveHttpRequestInterceptor;
import com.github.kristofa.brave.httpclient.BraveHttpResponseInterceptor;
import com.github.kristofa.brave.servlet.BraveServletFilter;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zipkin.Span;
import zipkin.reporter.AsyncReporter;
import zipkin.reporter.Reporter;
import zipkin.reporter.Sender;
import zipkin.reporter.okhttp3.OkHttpSender;

@Configuration
public class ZipConfig {

    @Value("${brave.name}")
    private String applicationName;
    @Value("${http.sender.address}")
    private String sendAddress;

    /**
     * Brave各工具类的封装
     *
     * @return Brave
     */
    @Bean
    public Brave brave() {
        Sender sender = OkHttpSender.create(sendAddress);
        Reporter<Span> reporter = AsyncReporter.builder(sender).build();
        Brave brave = new Brave.Builder(applicationName).reporter(reporter).build();
        return brave;
    }

    /**
     * 拦截器,需要serverRequestInterceptor,serverResponseInterceptor 分别完成sr和ss操作
     *
     * @param brave
     * @return
     */
    @Bean
    public BraveServletFilter braveServletFilter(Brave brave) {
        return BraveServletFilter.create(brave);
    }

    /**
     * httpClient客户端,需要clientRequestInterceptor,clientResponseInterceptor分别完成cs和cr操作
     *
     * @param brave
     * @return
     */
    @Bean
    public CloseableHttpClient closeableHttpClient(Brave brave) {
        CloseableHttpClient httpClient = HttpClients.custom()
                .addInterceptorFirst(BraveHttpRequestInterceptor.create(brave))
                .addInterceptorFirst(BraveHttpResponseInterceptor.create(brave))
                .build();
        return httpClient;
    }

}

说明:
1.注入的参数为该项目的名称,以及zipkin服务的地址
2.第一个bean是配置发送到zipkin的一些参数,生成一个全局的brave;
3.第二个bean是一个filter,这里配置了对request和response的封装,主要是获取和设置traceid等的一些追踪参数;
4.第三个bean是一个配置了request和response拦截器的httpclient,以供程序内部的http调用,否则无法追踪这部分的请求;

注意:如果是mvc框架的话需要在web.xml文件里加上

<!--zipkin链路追踪-->
  <filter>
    <filter-name>braveServletFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <async-supported>true</async-supported>
  </filter>
  <filter-mapping>
    <filter-name>braveServletFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>

如果是boot框架的话需要在配置类里面加上

  @Bean
    public FilterRegistrationBean testFilterRegistration(BraveServletFilter braveServletFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(braveServletFilter);
        registration.addUrlPatterns("/*");
        registration.setName("braveServletFilter");
        registration.setOrder(1);
        return registration;
    }

作用都是注册过滤器;

接下去做dubbo的集成

消费者端:

package com.rt.platform.infosys.base.common.zipkinconfig;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.alibaba.fastjson.JSONObject;
import com.github.kristofa.brave.*;
import com.github.kristofa.brave.internal.Nullable;
import com.github.kristofa.brave.internal.Util;
import com.rt.platform.infosys.base.common.utils.BasePropertiesUtil;
import com.twitter.zipkin.gen.Span;
import zipkin.reporter.AsyncReporter;
import zipkin.reporter.Reporter;
import zipkin.reporter.Sender;
import zipkin.reporter.okhttp3.OkHttpSender;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

@Activate(group = Constants.CONSUMER)
public class DrpcClientInterceptor implements Filter {

    private final ClientRequestInterceptor clientRequestInterceptor;
    private final ClientResponseInterceptor clientResponseInterceptor;
    private final ClientSpanThreadBinder clientSpanThreadBinder;

    public DrpcClientInterceptor() {
        String sendUrl = BasePropertiesUtil.getProperty(ZipkinConstants.SEND_ADDRESS);
        Sender sender = OkHttpSender.create(sendUrl);
        Reporter<zipkin.Span> reporter = AsyncReporter.builder(sender).build();
        String application = BasePropertiesUtil.getProperty(ZipkinConstants.BRAVE_NAME);
        Brave brave = new Brave.Builder(application).reporter(reporter).build();
        this.clientRequestInterceptor = Util.checkNotNull(brave.clientRequestInterceptor(), null);
        this.clientResponseInterceptor = Util.checkNotNull(brave.clientResponseInterceptor(), null);
        this.clientSpanThreadBinder = Util.checkNotNull(brave.clientSpanThreadBinder(), null);
    }


    @Override
    public Result invoke(Invoker<?> arg0, Invocation arg1) throws RpcException {
        clientRequestInterceptor.handle(new GrpcClientRequestAdapter(arg1));
        Map<String, String> att = arg1.getAttachments();
        final Span currentClientSpan = clientSpanThreadBinder.getCurrentClientSpan();
        Result result;
        try {
            result = arg0.invoke(arg1);
            clientSpanThreadBinder.setCurrentSpan(currentClientSpan);
            clientResponseInterceptor.handle(new GrpcClientResponseAdapter(result));
        } finally {
            clientSpanThreadBinder.setCurrentSpan(null);
        }
        return result;
    }

    static final class GrpcClientRequestAdapter implements ClientRequestAdapter {
        private Invocation invocation;

        public GrpcClientRequestAdapter(Invocation invocation) {
            this.invocation = invocation;
        }

        @Override
        public String getSpanName() {
            String ls = invocation.getMethodName();
            String serviceName = ls == null ? "unkown" : ls;
            return serviceName;
        }

        @Override
        public void addSpanIdToRequest(@Nullable SpanId spanId) {
            Map<String, String> at = this.invocation.getAttachments();
            if (spanId == null) {
                at.put("Sampled", "0");
            } else {
                at.put("Sampled", "1");
                at.put("TraceId", spanId.traceIdString());
                at.put("SpanId", IdConversion.convertToString(spanId.spanId));
                if (spanId.nullableParentId() != null) {
                    at.put("ParentSpanId", IdConversion.convertToString(spanId.parentId));
                }
            }
        }


        @Override
        public Collection<KeyValueAnnotation> requestAnnotations() {
            Object[] arguments = invocation.getArguments();
//            Map data = ls.getData();
            KeyValueAnnotation an = KeyValueAnnotation.create("params", JSONObject.toJSONString(arguments));
            return Collections.singletonList(an);
        }

        @Override
        public com.twitter.zipkin.gen.Endpoint serverAddress() {
            return null;
        }
    }

    static final class GrpcClientResponseAdapter implements ClientResponseAdapter {

        private final Result result;

        public GrpcClientResponseAdapter(Result result) {
            this.result = result;
        }

        @Override
        public Collection<KeyValueAnnotation> responseAnnotations() {
            return Collections.<KeyValueAnnotation>emptyList();
            /*
            return !result.hasException()
                ? Collections.<KeyValueAnnotation>emptyList()
                : Collections.singletonList(KeyValueAnnotation.create("error", result.getException().getMessage()));
                */
        }
    }
}

然后在消费者端的com.alibaba.dubbo.rpc.Filter文件里加上traceFilterc=xxx.xxx.xxx.DrpcClientInterceptor

生成端:

package com.rt.platform.infosys.base.common.zipkinconfig;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.github.kristofa.brave.*;
import com.rt.platform.infosys.base.common.utils.BasePropertiesUtil;
import zipkin.reporter.AsyncReporter;
import zipkin.reporter.Reporter;
import zipkin.reporter.Sender;
import zipkin.reporter.okhttp3.OkHttpSender;

import java.net.SocketAddress;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import static com.github.kristofa.brave.IdConversion.convertToLong;

@Activate(group = Constants.PROVIDER)
public class DrpcServerInterceptor implements Filter {

    private final ServerRequestInterceptor serverRequestInterceptor;
    private final ServerResponseInterceptor serverResponseInterceptor;

    public DrpcServerInterceptor() {
        String sendUrl = BasePropertiesUtil.getProperty(ZipkinConstants.SEND_ADDRESS);
        Sender sender = OkHttpSender.create(sendUrl);
        Reporter<zipkin.Span> reporter = AsyncReporter.builder(sender).build();
        String application = BasePropertiesUtil.getProperty(ZipkinConstants.BRAVE_NAME);//RpcContext.getContext().getUrl().getParameter("application");
        Brave brave = new Brave.Builder(application).reporter(reporter).build();
        this.serverRequestInterceptor = brave.serverRequestInterceptor();
        this.serverResponseInterceptor = brave.serverResponseInterceptor();
    }

    @Override
    public Result invoke(Invoker<?> arg0, Invocation arg1) throws RpcException {
        serverRequestInterceptor.handle(new DrpcServerRequestAdapter(arg1));
        Result result ;
        try {
            result =  arg0.invoke(arg1);
             serverResponseInterceptor.handle(new GrpcServerResponseAdapter(result));
        } finally {

        }
        return result;
    }

    static final class DrpcServerRequestAdapter implements ServerRequestAdapter {
        private Invocation invocation;
        DrpcServerRequestAdapter(Invocation invocation) {
            this.invocation = invocation;
        }

     @Override
        public TraceData getTraceData() {
            //Random randoml = new Random();
            Map<String,String> at = this.invocation.getAttachments();
            String sampled = at.get("Sampled");
            String parentSpanId = at.get("ParentSpanId");
            String traceId = at.get("TraceId");
            String spanId = at.get("SpanId");

            // Official sampled value is 1, though some old instrumentation send true
            Boolean parsedSampled = sampled != null
                ? sampled.equals("1") || sampled.equalsIgnoreCase("true")
                : null;

            if (traceId != null && spanId != null) {
                return TraceData.create(getSpanId(traceId, spanId, parentSpanId, parsedSampled));
            } else if (parsedSampled == null) {
                return TraceData.EMPTY;
            } else if (parsedSampled.booleanValue()) {
                // Invalid: The caller requests the trace to be sampled, but didn't pass IDs
                return TraceData.EMPTY;
            } else {
                return TraceData.NOT_SAMPLED;
            }
        }

       @Override
        public String getSpanName() {
             String ls = invocation.getMethodName();
             String serviceName = ls == null?"unkown":ls;
             return serviceName;
        }

        @Override
        public Collection<KeyValueAnnotation> requestAnnotations() {
            SocketAddress socketAddress = null;
            if (socketAddress != null) {
                KeyValueAnnotation remoteAddrAnnotation = KeyValueAnnotation.create(
                    "DRPC_REMOTE_ADDR", socketAddress.toString());
                return Collections.singleton(remoteAddrAnnotation);
            } else {
                return Collections.emptyList();
            }
        }
    }

    static final class GrpcServerResponseAdapter implements ServerResponseAdapter {

        final Result result;

        public GrpcServerResponseAdapter(Result result) {
            this.result = result;
        }

        @SuppressWarnings("unchecked")
        @Override
        public Collection<KeyValueAnnotation> responseAnnotations() {
            return !result.hasException()
                ? Collections.<KeyValueAnnotation>emptyList()
                : Collections.singletonList(KeyValueAnnotation.create("error", result.getException().getMessage()));
        }

    }

    static SpanId getSpanId(String traceId, String spanId, String parentSpanId, Boolean sampled) {
        return SpanId.builder()
            .traceIdHigh(traceId.length() == 32 ? convertToLong(traceId, 0) : 0)
            .traceId(convertToLong(traceId))
            .spanId(convertToLong(spanId))
            .sampled(sampled)
            .parentId(parentSpanId == null ? null : convertToLong(parentSpanId)).build();
    }
}

然后在生产者端的com.alibaba.dubbo.rpc.Filter文件里加上traceFilters=xxx.xxx.xxx.DrpcServerInterceptor

启动项目进行接口访问,再登录zipkin服务的地址就能看到调用各个服务的情况。

注意:

在进行dubbo集成的时候,注意,filter的配置,扩站文件中配置好以后,对应的xml中就不要在配置filter的名字在,否则将出现请求无法连在一起。加入提供者又是消费者时还需要添加消费者的过滤器。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容