如何将 dubbo filter 拦截器原理运用到日志拦截器中?

业务背景

我们希望可以在使用日志拦截器时,定义属于自己的拦截器方法。

实现的方式有很多种,我们分别来看一下。

拓展阅读

java 注解结合 spring aop 实现自动输出日志

java 注解结合 spring aop 实现日志traceId唯一标识

java 注解结合 spring aop 自动输出日志新增拦截器与过滤器

如何动态修改 spring aop 切面信息?让自动日志输出框架更好用

如何将 dubbo filter 拦截器原理运用到日志拦截器中?

chain

v1-基本版本

接口

最常见的定义方式,在方法执行前后,异常,finally 提供钩子函数。

package com.github.houbb.auto.log.api;/*** autoLog 拦截器* @author binbin.hou* @since 0.0.10*/
public interface IAutoLogInterceptor {/*** 执行之前* @param interceptorContext 拦截器上下文* @since 0.0.10*/void beforeHandle(IAutoLogInterceptorContext interceptorContext);/*** 执行之后* @param interceptorContext 拦截器上下文* @param result 方法执行结果* @since 0.0.10*/void afterHandle(IAutoLogInterceptorContext interceptorContext,final Object result);/*** 异常处理* @param interceptorContext 拦截器上下文* @param exception 异常* @since 0.0.10*/void exceptionHandle(IAutoLogInterceptorContext interceptorContext, Exception exception);/*** finally 中执行的代码* @param interceptorContext 拦截器上下文* @since 0.0.10*/void finallyHandle(IAutoLogInterceptorContext interceptorContext);}

工具中统一使用拦截器

package com.github.houbb.auto.log.core.core.impl;
/*** @author binbin.hou* @since 0.0.7*/
public class SimpleAutoLog implements IAutoLog {/*** 自动日志输出** @param context 上下文* @return 结果* @since 0.0.7*/@Overridepublic Object autoLog(IAutoLogContext context) throws Throwable {//1. 日志唯一标识// ... 省略List<IAutoLogInterceptor> autoLogInterceptors = null;try {// ... 省略其他逻辑// 获取拦截器autoLogInterceptors = autoLogInterceptors(autoLog);//1.2 autoLogif(CollectionUtil.isNotEmpty(autoLogInterceptors)) {for(IAutoLogInterceptor interceptor : autoLogInterceptors) {interceptor.beforeHandle(autoLogContext);}}//2. 执行结果Object result = context.process();//2.1 方法执行后if(CollectionUtil.isNotEmpty(autoLogInterceptors)) {for(IAutoLogInterceptor interceptor : autoLogInterceptors) {interceptor.afterHandle(autoLogContext, result);}}//2.2 返回方法return result;} catch (Exception exception) {if(CollectionUtil.isNotEmpty(autoLogInterceptors)) {for(IAutoLogInterceptor interceptor : autoLogInterceptors) {interceptor.exceptionHandle(autoLogContext, exception);}}throw new AutoLogRuntimeException(exception);} finally {// 先执行日志if(CollectionUtil.isNotEmpty(autoLogInterceptors)) {for(IAutoLogInterceptor interceptor : autoLogInterceptors) {interceptor.finallyHandle(autoLogContext);}}}}/*** 创建拦截器列表* @param autoLog 注解* @return 结果* @since 0.0.10*/private List<IAutoLogInterceptor> autoLogInterceptors(final AutoLog autoLog) {List<IAutoLogInterceptor> resultList = new ArrayList<>();if(ObjectUtil.isNull(autoLog)) {return resultList;}Class<? extends IAutoLogInterceptor>[] interceptorClasses = autoLog.interceptor();if(ArrayUtil.isEmpty(interceptorClasses)) {return resultList;}// 循环创建for(Class<? extends IAutoLogInterceptor> clazz : interceptorClasses) {IAutoLogInterceptor traceIdInterceptor = createAutoLogInterceptor(clazz);resultList.add(traceIdInterceptor);}return resultList;}/*** 创建拦截器* @param clazz 类* @return 实体* @since 0.0.10*/private IAutoLogInterceptor createAutoLogInterceptor(final Class<? extends IAutoLogInterceptor> clazz) {if(IAutoLogInterceptor.class.equals(clazz)) {return new AutoLogInterceptor();}return ClassUtil.newInstance(clazz);}}

自定义实现拦截器

我们想自定义拦截器方法时,只需要实现对应的接口即可。

/*** 自定义日志拦截器* @author binbin.hou* @since 0.0.12*/
public class MyAutoLogInterceptor extends AbstractAutoLogInterceptor {@Overrideprotected void doBefore(AutoLog autoLog, IAutoLogInterceptorContext context) {System.out.println("自定义入参:" + Arrays.toString(context.filterParams()));}@Overrideprotected void doAfter(AutoLog autoLog, Object result, IAutoLogInterceptorContext context) {System.out.println("自定义出参:" + result);}@Overrideprotected void doException(AutoLog autoLog, Exception exception, IAutoLogInterceptorContext context) {System.out.println("自定义异常:");exception.printStackTrace();}}

方法的不足

这种方式可以实现常见的功能,但是依然不够优雅。

我们还是无法非常灵活的定义自己的拦截器实现,就像我们使用 aop 增强,或者 dubbo filter 一样。

感兴趣的小伙伴可以移步学习一下,此处不做展开。

Dubbo-02-dubbo invoke filter 链式调用原理

模拟 dubbo filter

实现 Invoker

类似 dubbo invoke,直接在以前的类中初始化即可。

AutoLogInvoker autoLogInvoker = new AutoLogInvoker(context);
Invocation invocation = new CommonInvocation();
invocation.setAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_CONTEXT, context);
invocation.setAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_START_TIME, startTimeMills);
invocation.setAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_FILTER_PARAMS, filterParams);Invoker chainInvoker = InvokerChainBuilder.buildInvokerChain(autoLogInvoker);
Result autoLogResult = chainInvoker.invoke(invocation);

其中 AutoLogInvoker 只是对方法的执行。

实现拦截器

这是的方法增强就是类似 dubbo filter 链式调用实现的,自定义的时候也会方便很多。

不需要拘泥于方法的执行位置,直接编写我们的增强逻辑即可。

package com.github.houbb.auto.log.core.support.interceptor.chain;import com.alibaba.fastjson.JSON;
import com.github.houbb.auto.log.annotation.AutoLog;
import com.github.houbb.auto.log.api.IAutoLogContext;
import com.github.houbb.auto.log.core.constant.AutoLogAttachmentKeyConst;
import com.github.houbb.common.filter.annotation.FilterActive;
import com.github.houbb.common.filter.api.CommonFilter;
import com.github.houbb.common.filter.api.Invocation;
import com.github.houbb.common.filter.api.Invoker;
import com.github.houbb.common.filter.api.Result;
import com.github.houbb.common.filter.exception.CommonFilterException;
import com.github.houbb.heaven.util.lang.StringUtil;
import com.github.houbb.heaven.util.lang.reflect.ClassUtil;
import com.github.houbb.heaven.util.lang.reflect.ReflectMethodUtil;
import com.github.houbb.id.api.Id;
import com.github.houbb.id.core.core.Ids;
import com.github.houbb.id.core.util.IdThreadLocalHelper;
import com.github.houbb.log.integration.core.Log;
import com.github.houbb.log.integration.core.LogFactory;import java.lang.reflect.Method;/*** 默认的日志拦截器*/
@FilterActive(order = Integer.MIN_VALUE)
public class AutoLogCommonFilter implements CommonFilter {private static final Log LOG = LogFactory.getLog(AutoLogCommonFilter.class);/*** 是否需要处理日志自动输出* @param autoLog 上下文* @return 结果* @since 0.0.10*/protected boolean enableAutoLog(final AutoLog autoLog) {if(autoLog == null) {return false;}return autoLog.enable();}/*** 获取方法描述* @param method 方法* @param autoLog 注解* @return 结果* @since 0.0.10*/protected String getMethodDescription(Method method, AutoLog autoLog) {String methodName = ReflectMethodUtil.getMethodFullName(method);if(autoLog != null&& StringUtil.isNotEmpty(autoLog.description())) {methodName += "#" + autoLog.description();}return methodName;}/*** 获取 traceId* @param autoLog 日志注解* @return 结果* @since 0.0.10*/protected String getTraceId(AutoLog autoLog) {//1. 优先看当前线程中是否存在String oldId = IdThreadLocalHelper.get();if(StringUtil.isNotEmpty(oldId)) {return formatTraceId(oldId);}//2. 返回对应的标识Id id = getActualTraceId(autoLog);return formatTraceId(id.id());}/*** 获取日志跟踪号策略* @param autoLog 注解* @return 没结果*/protected Id getActualTraceId(AutoLog autoLog) {Class<? extends Id> idClass = autoLog.traceId();if(Id.class.equals(idClass)) {return Ids.uuid32();}return ClassUtil.newInstance(autoLog.traceId());}/*** 格式化日志跟踪号* @param id 跟踪号* @return 结果* @since 0.0.16*/protected String formatTraceId(String id) {return String.format("[%s] ", id);}@Overridepublic Result invoke(Invoker invoker, Invocation invocation) throws CommonFilterException {final IAutoLogContext autoLogContext = (IAutoLogContext) invocation.getAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_CONTEXT);final AutoLog autoLog = autoLogContext.autoLog();final boolean enableAutoLog = enableAutoLog(autoLog);if(!enableAutoLog) {return invoker.invoke(invocation);}final String description = getMethodDescription(autoLogContext.method(), autoLog);// 默认从上下文中取一次String traceId = IdThreadLocalHelper.get();try {// 设置 traceId 策略if(autoLog.enableTraceId()) {Id id = getActualTraceId(autoLog);traceId = id.id();invocation.setAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_TRACE_ID, traceId);IdThreadLocalHelper.put(traceId);}Result result = invoker.invoke(invocation);// 日志增强logForEnhance(autoLogContext, traceId, description, result.getValue(), invocation);return result;} catch (Exception e) {if (autoLog.exception()) {String message = String.format("[TID=%s][EXCEPTION=%s]", traceId, e.getMessage());LOG.error(message, e);}throw new RuntimeException(e);}}/*** 增强日志输出* @param autoLogContext 上下文* @param traceId 日志跟踪号* @param description 方法描述* @param resultValue 返回值* @param invocation 调用上下文*/private void logForEnhance(final IAutoLogContext autoLogContext,final String traceId,final String description,final Object resultValue,Invocation invocation) {final AutoLog autoLog = autoLogContext.autoLog();StringBuilder logBuilder = new StringBuilder();logBuilder.append(String.format("[TID=%s]", traceId));logBuilder.append(String.format("[METHOD=%s]", description));// 入参if(autoLog.param()) {Object[] params = (Object[]) invocation.getAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_FILTER_PARAMS);logBuilder.append(String.format("[PARAM=%s]", JSON.toJSONString(params)));}// 出参if (autoLog.result()) {logBuilder.append(String.format("[RESULT=%s]", JSON.toJSONString(resultValue)));}// 耗时//3.1 耗时 & 慢日志if(autoLog.costTime()) {long startTime = (long) invocation.getAttachment(AutoLogAttachmentKeyConst.AUTO_LOG_START_TIME);long costTime = System.currentTimeMillis() - startTime;logBuilder.append(String.format("[COST=%d ms]", costTime));// 慢日志final long slowThreshold = autoLog.slowThresholdMills();if(slowThreshold > 0 && costTime > slowThreshold) {logBuilder.append(String.format("[SLOW-THRESHOLD=%s]", slowThreshold));}}// 输出日志LOG.info(logBuilder.toString());}}

开源地址

为了便于大家学习,项目已开源。

Github: https://github.com/houbb/auto-log

Gitee: https://gitee.com/houbinbin/auto-log

小结

dubbo filter 模式非常的优雅,以前一直只是学习,没有将其应用到自己的项目中。

提供的便利性是非常强大的,值得学习运用。

参考资料

auto-log

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/25047.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

思科单臂路由、lacp链路聚合、NAT实验

实验拓扑图&#xff1a; 实验目的&#xff1a; 如图所示配置相应IP地址和VLAN&#xff0c;并通过在AR1上配置单臂路由&#xff0c;实现VLAN10和VLAN20的主机能够在VLAN间通信&#xff1b;在SW1和SW2的三条链路实施链路聚合&#xff0c;使用静态LACP模式&#xff0c;使一条链…

【Python文件新建、打开、读写、保存、查看信息操作】

【Python文件新建、打开、读写、保存、查看信息操作】 1 指定格式打开文件2 关闭文件3 使用with语句保证新建、打开后关闭文件&#xff0c;避免异常4 写入文件5 使用with语句保证打开后关闭文件&#xff0c;避免异常6 复制文件7 移动文件8 重名名9 判断文件或文件夹是否存在10 …

打开虚拟机进行ip addr无网络连接

打开虚拟机进行ip addr无网络连接 参考地址&#xff1a;https://www.cnblogs.com/Courage129/p/16796390.html 打开虚拟机进行ip addr无网络连接。 输入下面的命令&#xff0c; sudo dhclient ens33 会重新分配一个新的ip地址&#xff0c;但是此时的ip地址已经不是我原先在虚…

Visual Studio在Debug模式下,MFC工程中包含Eigen库时的定义冲突的问题

Visual Studio在Debug模式下&#xff0c;MFC工程中包含Eigen库时的定义冲突的问题 报错信息 Eigen\src\Core\PlainObjectBase.h(143,5): error C2061: 语法错误: 标识符“THIS_FILE” Eigen\src\Core\PlainObjectBase.h(143,1): error C2333: “Eigen::PlainObjectBase::opera…

LeetCode 热题 100 JavaScript--102. 二叉树的层序遍历

给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;[[3],[9,20],[15,7]] 示例 2&#xff1a; 输入&#xff1a;root [1…

Windows 主机的VMware 虚拟机访问 wsl-ubuntu 的 API 服务

Windows 主机的VMware 虚拟机访问 wsl-ubuntu 的 API 服务 0. 背景1. 设置2. 删除 0. 背景 需要从Windows 主机的VMware 虚拟机访问 wsl-ubuntu 的 API 服务。 1. 设置 Windows 主机的IP&#xff1a;192.168.31.20 wsl-ubuntu Ubuntu-22.04 的IP&#xff1a;172.29.211.52 &…

Linux软件实操

systemctl命令 Linux系统的很多内置或第三方的软件均支持使用systemctl命令控制软件(服务)的启动、停止、开机自启 systemctl start(启动) 或 stop(关闭) 或 status(查看状态) 或 enable(开启开机自启) disable(关闭开机自启) 服务名: 控制服务的状态 系统内置的服务: Netwo…

React 18 响应事件

参考文章 响应事件 使用 React 可以在 JSX 中添加 事件处理函数。其中事件处理函数为自定义函数&#xff0c;它将在响应交互&#xff08;如点击、悬停、表单输入框获得焦点等&#xff09;时触发。 添加事件处理函数 如需添加一个事件处理函数&#xff0c;需要先定义一个函数…

基于RASC的keil电子时钟制作(瑞萨RA)(10)----读取DHT11温湿度数据

基于RASC的keil电子时钟制作10_读取DHT11温湿度数据 概述硬件准备视频教程产品参数电路设置数据格式数据读取步骤GPIO设置读取温湿度数据dht11.cdht11.h主程序 概述 本篇介绍如何驱动DH11湿度传感器同时实现当前串口数据打印。 DHT11 数字温湿度传感器是一款含有已校准数字信号…

系列2-MYSQL通用调优策略

系列2-MYSQL通用调优策略-2 1、硬件层面 BIOS-CPU电源管理-Performance Per Watt Optimized(DAPC)&#xff0c;发挥cpu的最大性能。关闭C-states和C1E&#xff0c;开启Turbo Boots可以将CPU保持运行全核睿频BIOS-Memory Frequency&#xff08;内存频率&#xff09;-选择Maxim…

RabbitMQ:概念和安装,简单模式,工作,发布确认,交换机,死信队列,延迟队列,发布确认高级,其它知识,集群

1. 消息队列 1.0 课程介绍 1.1.MQ 的相关概念 1.1.1.什么是MQ MQ(message queue&#xff1a;消息队列)&#xff0c;从字面意思上看&#xff0c;本质是个队列&#xff0c;FIFO 先入先出&#xff0c;只不过队列中存放的内容是message 而已&#xff0c;还是一种跨进程的通信机制…

XML 学习笔记 7:XSD

本文章内容参考自&#xff1a; W3school XSD 教程 Extensible Markup Language (XML) 1.0 (Second Edition) XML Schema 2001 XML Schema Part 2: Datatypes Second Edition 文章目录 1、XSD 是什么2、XSD 内置数据类型 - built-in datatypes2.1、基本数据类型 19 种2.1.1、基本…

MySQL日期常见的函数

-- 获取当天日期 -- 2023-06-20 select curdate();-- 获取当天年月日时分秒 select now();-- 日期运算 -- 2024-06-20 17:04:17 select date_add(now(),interval 1 year);-- 日期比较 -- 0 select datediff(now(),now());-- 日期MySQL对于日期类型数据如何查询 -- 获取指定日期…

【SpringCloud 面试题整理-超级有用】

文章目录 1、什么是Spring Cloud?2、使用Spring Cloud有什么优势&#xff1f;3、服务注册和发现是什么意思&#xff1f;Spring Cloud如何实现&#xff1f;4、负载平衡的意义什么&#xff1f;5、什么是Hystrix&#xff1f;它如何实现容错?6、什么是Hystrix 断路器&#xff1f;…

Goland搭建远程Linux开发

Windows和Linux都需要先构建好go环境&#xff0c;启用ssh服务。 打开Windows上的Goland&#xff0c;建立项目。 点击添加配置&#xff0c;选择go构建 点击运行于&#xff0c;选择ssh 填上Linux机器的IP地址和用户名 输入密码 没有问题 为了不让每次运行程序和调试程序都生…

在汇编语言中调用C语言的函数

在汇编语言中调用C语言的函数&#xff0c;需要在汇编语言中IMPORT对应的C语言函数名&#xff0c;然后将C语言的代码放在一个独立的C语言文件中进行编译&#xff0c;剩下的工作由连接器来处理。 实例代码&#xff1a; ;the details of parameters transfer comes from ATPCS ;i…

华为OD机试真题【开心消消乐】

1、题目描述 【开心消消乐】 给定一个N行M列的二维矩阵&#xff0c;矩阵中每个位置的数字取值为0或1。矩阵示例如&#xff1a; 1100 0001 0011 1111 现需要将矩阵中所有的1进行反转为0&#xff0c;规则如下&#xff1a; 1&#xff09; 当点击一个1时&#xff0c;该1便被反转为…

前端个人年度工作述职报告(二十篇)

前端个人年度工作述职报告篇1 尊敬的各位领导、各位同仁&#xff1a; 大家好!按照20__年度我公司就职人员工作评估的安排和要求&#xff0c;我认真剖析、总结了自己的工作情况&#xff0c;现将本人工作开展情况向各位领导、同仁做以汇报&#xff0c;有不妥之处&#xff0c;希…

人工智能与物理学(软体机器人能量角度)的结合思考

前言 好久没有更新我的CSDN博客了&#xff0c;细细数下来已经有了16个月。在本科时期我主要研究嵌入式&#xff0c;研究生阶段对人工智能感兴趣&#xff0c;看了一些这方面的论文和视频&#xff0c;因此用博客记录了一下&#xff0c;后来因为要搞自己的研究方向&#xff0c;就…

【C# 基础精讲】C# 开发环境搭建(Visual Studio等)

安装C#开发环境是开始学习和使用C#编程的第一步。目前&#xff0c;最常用的C#开发环境是Microsoft Visual Studio&#xff0c;它是一套强大的集成开发环境&#xff08;IDE&#xff09;&#xff0c;提供了丰富的工具和功能&#xff0c;使开发C#应用程序变得更加便捷。以下是安装…