美文网首页
springboot dubbo 全局拦截器

springboot dubbo 全局拦截器

作者: zt_sole | 来源:发表于2024-03-21 16:28 被阅读0次

    1. 增加 DubboExceptionFilter

    
    import cn.hutool.core.lang.UUID;
    import com.alibaba.dubbo.rpc.*;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang.exception.ExceptionUtils;
    import org.apache.dubbo.rpc.service.GenericService;
    
    @Slf4j
    public class DubboExceptionFilter implements Filter{
        @Override
        public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    
                Result result = invoker.invoke(invocation);
                if(result.hasException() && GenericService.class !=invoker.getInterface()){
                    // 存在异常进行异常处理
                    String uid="ERROR_"+UUID.fastUUID().toString().split("-")[4];
                    String message=result.getException().getMessage()+"["+uid+"]";
                    // 打印异常栈信息
                    log.error("{}:{}", uid,ExceptionUtils.getFullStackTrace(result.getException()));
                    // 重置异常抛出,可以根据业务重新定义异常信息
                    result.setException(new Exception(message));
                }
    
                return result;
        }
    }
    

    2.增加 com.alibaba.dubbo.rpc.Filter文件并写入以下内容

    dubboExceptionFilter=com.test.config.DubboExceptionFilter
    

    com.test.config.DubboExceptionFilter 是第一步中的DubboExceptionFilter 完整路径。需要更加自己的包路径进行调整
    dubboExceptionFilter 拦截器别名,需要配置在yaml文件中

    image.png

    3. yaml 文件新增配置

    dubbo:
      provider:
        # dubboExceptionFilter 对应第二步骤中的key,注意不要写错了
        filter: dubboExceptionFilter
      payload:
        default: -1
    

    相关文章

      网友评论

          本文标题:springboot dubbo 全局拦截器

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