使用dubbo过滤器记录请求时长+记录日志id

最近公司要做系统优化,但是项目并没有数据分析埋点,接口响应时间没有做记录,只能从线上出现的问题来做具体的分析。
由此提出通过记录日志的形式做接口响应时长,首先就是想到的使用filter,我们公司框架使用的zk+dubbo,正好使用到了dubbo的filter能够精确到具体方法上
我们做法 使用拦截器记录接口的响应时间、创建日志id 方便后期日志查询 使用filter记录提供方服务响应时间
代码:

Interceptor

@Component
@Slf4j
public class InterceptorByDubbo implements HandlerInterceptor {
    public static ThreadLocal threadLocal = new ThreadLocal();
    Long start;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        start = System.currentTimeMillis();
        //创建日志id
        threadLocal.set(UUID.randomUUID().toString());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    //清除变量 防止oom
        threadLocal.remove();
        // 记录接口相应时长
        log.info("接口[ {} ] 耗时 [ {} ]",request.getRequestURI(),System.currentTimeMillis() - start);
    }
}

filter

//order 排名 越小越靠前
//greop 触发的时机
@Slf4j
//@Activate(group = {CommonConstants.CONSUMER,Constants.TOKEN_KEY},order = 10000)
@Activate(group = {CommonConstants.CONSUMER,CommonConstants.PROVIDER},order = 10000)
public class TestDubboFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result ;
        long start = System.currentTimeMillis();
        if (RpcContext.getContext().isConsumerSide()){
            result = invoker.invoke(invocation);
            log.info("dubbo Filter Log consumer log 打印 耗时[ {} ] LogId [ {} ] 方法名称[ {} ]",System.currentTimeMillis() -start, InterceptorByDubbo.threadLocal.get(),invocation.getMethodName());
        }else if (RpcContext.getContext().isProviderSide()){
            result = invoker.invoke(invocation);
            log.info("dubbo Filter Log provider log 打印 耗时[ {} ] LogId [ {} ] 方法名称[ {} ]",System.currentTimeMillis() -start, InterceptorByDubbo.threadLocal.get(),invocation.getMethodName());
        }else {
            log.info("日志打印了");
            result = invoker.invoke(invocation);
        }
        return result;
    }
}

创建dubo配置
在这里插入图片描述

这是自己着手做的一个小demo,大致的思路就是这样,可能具体细节还需要在优化,具体问题具体分析
自主学习 有不对的地方大神帮忙指点一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值