美文网首页Dubbo
dubbo链路跟踪

dubbo链路跟踪

作者: 楚1390 | 来源:发表于2019-02-18 09:49 被阅读0次

    没有使用框架,自己写的简单链路跟踪,主要是下面两个过滤器TraceRpcFilter、TraceHttpFilter 。

    @Activate(group = {Constants.CONSUMER,Constants.PROVIDER})

    public class TraceRpcFilter implements Filter {

        /**

        * 1、保证RpcContext中存在mdcData,为了下一次获取mdcData后写入到MDC

        * 2、保证MDC中存在mdcData,为了最终的日志打印输入

        * @param invoker

        * @param invocation

        * @return

        * @throws RpcException

        */

        public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

            //创建traceId

            TraceUtils.createTrace();

            //创建spanId

            TraceUtils.createSpan();

            //设置parentId

            TraceUtils.setParent();

            //设置其它信息

            TraceUtils.setRpcOthersInfo();

            return invoker.invoke(invocation);

        }

    }


    public class TraceHttpFilter extends OncePerRequestFilter implements Ordered {

        private static final Logger logger  = LoggerFactory.getLogger(TraceHttpFilter.class);

        @Autowired(required = false)

        private TraceLogInformation traceLogInformation;

        @Override

        public int getOrder() {

            return 0;

        }

        /***

        * 生成traceId和spanId,并写入slf4j的本地线程变量(也就意味着,请求中开启的线程和定时任务是得不到traceId和spanId的)

        * @Param [request, response, filterChain]

        * @return void

        **/

        @Override

        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

            try {

                String traceId = request.getHeader("x-http-trace");//nginx可能附加的请求头

                if (StringUtils.isEmpty(traceId)) {

                    MDC.put(TraceConstants.TRACE_ID, TraceUtils.getLogId());

                } else {

                    MDC.put(TraceConstants.TRACE_ID, traceId);

                }

                //初次调用,生成spanId

                MDC.put(TraceConstants.SPAN_ID, TraceUtils.getLogId());

                if (traceLogInformation != null) {

                    traceLogInformation.setLocalIp(AccessIpUtils.getLocalIp());//本地IP

                    traceLogInformation.setRemoteIp(AccessIpUtils.getRemoteIp(request));//访问IP

                    TraceUtils.setHttpOthersInfo(traceLogInformation);

                }

            }catch (Exception ex){

                logger.error("http请求过滤器处理异常:{}",ex.getMessage());

            }

            filterChain.doFilter(request ,response);

        }

    }


    public class AccessIpUtils {

        /***

        * X-Forwarded-For:    Squid 服务代理

        * Proxy-Client-IP:    apache 服务代理

        * WL-Proxy-Client-IP:  weblogic 服务代理

        * X-Real-IP:          nginx服务代理

        * HTTP_CLIENT_IP:      有些代理服务器

        *对http请求获取请求IP

        * @Param [request]

        * @return java.lang.String

        **/

        public static String getRemoteIp(HttpServletRequest request) {

            String ip = null;

            String ipAddresses = request.getHeader("X-Forwarded-For");

            if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {

                ipAddresses = request.getHeader("Proxy-Client-IP");

            }

            if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {

                ipAddresses = request.getHeader("WL-Proxy-Client-IP");

            }

            if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {

                ipAddresses = request.getHeader("HTTP_CLIENT_IP");

            }

            if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {

                ipAddresses = request.getHeader("X-Real-IP");

            }

            //有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP

            if (ipAddresses != null && ipAddresses.length() != 0) {

                ip = ipAddresses.split(",")[0];

            }

            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {

                ip = request.getRemoteAddr();

            }

            return ip;

        }

        public static String getLocalIp()throws UnknownHostException{

            return InetAddress.getLocalHost().getHostAddress();

        }

    }

    public class TraceConstants {

        public static final String TRACE_TEXT_FORMAT = "[TraceId:%s]";

        public static final String TRACE_ID =  "traceId2";

        public static final String SPAN_ID  =  "spanId2";

        public static final String PARENT_ID =  "parentId2";

        public static final String APP_FLAG = UUID.randomUUID().toString();

    }

    public class TraceUtils {

        /***

        * 通过UUID,生成traceId、spanId

        * @Param []

        * @return java.lang.String

        **/

        public static String getLogId(){

            return UUID.randomUUID().toString().replaceAll("-","");

        }

        /***

        * 生成TraceId,

        * 关键点:traceId不应该为空,仅从该点出发判断逻辑即可,不做任何其它逻辑上的判断

        * @Param []

        * @return void

        **/

        public static  void  createTrace(){

            String  rpcTraceId  =  RpcContext.getContext().getAttachment(TraceConstants.TRACE_ID);

            String  mdcTraceId  =  MDC.get(TraceConstants.TRACE_ID);

            if(StringUtils.isEmpty(mdcTraceId)&&StringUtils.isEmpty(rpcTraceId)){

                rpcTraceId  =  TraceUtils.getLogId();

                MDC.put(TraceConstants.TRACE_ID ,rpcTraceId);

                RpcContext.getContext().setAttachment(TraceConstants.TRACE_ID ,rpcTraceId);

            }else if(StringUtils.isEmpty(mdcTraceId)&&StringUtils.isNotEmpty(rpcTraceId)){

                MDC.put(TraceConstants.TRACE_ID ,rpcTraceId);

            }else if(StringUtils.isEmpty(rpcTraceId)&&StringUtils.isNotEmpty(mdcTraceId)){

                RpcContext.getContext().setAttachment(TraceConstants.TRACE_ID ,mdcTraceId);

            }

        }

        /***

        * 生成SpanId,

        * 关键点:一次调用的同一个服务中,spanId是不变的;不同的服务中,spanId是不一样的;另外,spanId不可能为空

        * @Param []

        * @return void

        **/

        public static  void  createSpan(){

            String  rpcSpanId  =  RpcContext.getContext().getAttachment(TraceConstants.SPAN_ID);

            String  mdcSpanId  =  MDC.get(TraceConstants.SPAN_ID);

            if(StringUtils.isEmpty(mdcSpanId)&&StringUtils.isEmpty(rpcSpanId)){

                rpcSpanId  =  TraceUtils.getLogId();

                MDC.put(TraceConstants.SPAN_ID ,rpcSpanId);

                RpcContext.getContext().setAttachment(TraceConstants.SPAN_ID ,rpcSpanId);

            } else if(StringUtils.isEmpty(mdcSpanId)&&StringUtils.isNotEmpty(rpcSpanId)){

                MDC.put(TraceConstants.SPAN_ID ,TraceUtils.getLogId());

            }

        }

        /***

        * 设置parentId

        * 关键点:同一个服务中的一次调用,parentId是不变的;其他情况下,parentId为上一次的spanId

        * @Param []

        * @return void

        **/

        public static  void setParent(){

            String mdcSpanId    =  MDC.get(TraceConstants.SPAN_ID);

            String  rpcSpanId  =  RpcContext.getContext().getAttachment(TraceConstants.PARENT_ID);

            if(StringUtils.isNotEmpty(mdcSpanId)){

                RpcContext.getContext().setAttachment(TraceConstants.PARENT_ID ,mdcSpanId);

            }

            if(StringUtils.isNotEmpty(rpcSpanId)){

                MDC.put(TraceConstants.PARENT_ID, rpcSpanId);

            }

        }

        /**

        * 应用名称、Ip等信息

        * @Param []

        * @return void

        **/

        public static  void setRpcOthersInfo(){

            String appName = RpcContext.getContext().getUrl().getParameter("application");

            String localIp = RpcContext.getContext().getLocalHost();

            String remoteIp = RpcContext.getContext().getRemoteHost();

            MDC.put("appName" ,appName);

            MDC.put("localIp2" ,localIp);

            MDC.put("remoteIp2",remoteIp);

        }

        /**

        * 应用名称、Ip等信息

        * @Param []

        * @return void

        **/

        public static  void setHttpOthersInfo(TraceLogInformation traceLogInformation){

            MDC.put("appName" ,traceLogInformation.getApplicationName());

            MDC.put("localIp" ,traceLogInformation.getLocalIp());

            MDC.put("remoteIp" ,traceLogInformation.getRemoteIp());

        }

    }

    相关文章

      网友评论

        本文标题:dubbo链路跟踪

        本文链接:https://www.haomeiwen.com/subject/fyioeqtx.html