博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自定义request链路跟踪
阅读量:7209 次
发布时间:2019-06-29

本文共 1944 字,大约阅读时间需要 6 分钟。

hot3.png

1.自定义注解类

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Trace {    String businessName() default "";}

2.在需要拦截的方法上加自定义注解

@Trace(businessName = "线上复核扫描出库单号")@Token@RequestMapping(value = "/mst-obd-review/checkorderno", method = {RequestMethod.POST, RequestMethod.GET})public RespJson checkorderno(@RequestParam("orderNo") String orderNo,HttpServletRequest request) {...

3.自定义拦截器

public class RpcTraceInterceptor extends HandlerInterceptorAdapter {    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        TraceContext traceContext = (TraceContext) TraceContext.ctx.get();        //清除traceid        traceContext.clear();        //重新生成traceid        MDC.put("traceId", traceContext.getTraceId());        return super.preHandle(request, response, handler);    }    @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {        //请求结束情况traceid        MDC.remove("traceId");        super.afterCompletion(request, response, handler, ex);    }}
public class TraceContext {    public static ThreadLocal ctx = new InheritableThreadLocal() { //此处用InheritableThreadLocal保证可以在子线程得到相同的traceId        @Override        protected TraceContext initialValue() {            return new TraceContext();        }    };    private String traceId;    public String getTraceId() {        if (traceId == null || "".equals(traceId)) {            int hashCodeV = UUID.randomUUID().toString().hashCode();            if (hashCodeV < 0) {//有可能是负数                hashCodeV = -hashCodeV;            }            // 0 代表前面补充0            // 4 代表长度为4            // d 代表参数为正数型            traceId = String.format("%012d", hashCodeV);        }        return traceId;    }    public void clear() {        traceId = null;    }}

转载于:https://my.oschina.net/u/2485283/blog/1859320

你可能感兴趣的文章
ElementUI的提示框的使用记录
查看>>
Linux c获取任意路径的硬盘使用情况
查看>>
ora-24550 signo=6 signo=11解决
查看>>
C# Bitmap长宽参数构造的图片对象的每个像素ARGB都是0
查看>>
android timed gpio (linux 3.0.0) 受时钟控制的gpio【转】
查看>>
idea 关闭代码自动折叠,形参提示,行数栏图标,启动不默认打开上次的项目...
查看>>
mybatis 获取insert返回的主键
查看>>
R绘图 第八篇:绘制饼图(ggplot2)
查看>>
git:could not open a connection to your authentication agent
查看>>
七牛云的使用
查看>>
MySQL问答整理
查看>>
Java JSONArray的封装与解析
查看>>
Linux系统中查找、删除重复文件,释放磁盘空间。
查看>>
phpstudy安装好之后mysql无法启动(亲测可行)
查看>>
网易云terraform实践
查看>>
attenuation
查看>>
vue中$router和$route的区别
查看>>
【转】APK反编译
查看>>
uni-app 如何引入全局方法或变量?
查看>>
mac下python2.x和python3.x的安装方法和升级方法/卸载
查看>>