如何判断这个方法的调用来自dubbo consumer

本文介绍了通过四种方法来判断当前调用是否为Dubbo框架内的服务提供者或消费者:利用Thread.currentThread().getName()检查线程名称;通过org.apache.dubbo.rpc.RpcContext获取上下文并判断是否为提供者侧;通过分析堆栈跟踪来识别Dubbo相关调用;使用反射机制获取调用者类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个是比较好玩的一个问题? 如何判断呢?

  • 1、Thread.name
Thread.currentThread().getName().startsWith("DubboServerHandler")
  • 2、org.apache.dubbo.rpc.RpcContext.getContext()
 org.apache.dubbo.common.URL url = org.apache.dubbo.rpc.RpcContext.getContext().getUrl();
if (url !=null &&  RpcContext.getContext().isProviderSide()) {
    System.out.println("this is consumer");
}
  • 3、堆栈判断最后的几个是否存在dubbo的调用
public static boolean isDubboInvoke() {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

    boolean result = false;
    int count = 0;
    for (int index = stackTrace.length - 1; index >= 0; index--) {
        count++;
        if (stackTrace[index].getClassName().contains("org.apache.dubbo.remoting")) {
            result = true;
            break;
        }
        if (count > MAX_LOOP) {
            break;
        }
    }
    return result;

}
  • 4 sun.reflect.Reflection

https://blog.csdn.net/weixin_34203832/article/details/93609519

 Class<?> callerClass = sun.reflect.Reflection.getCallerClass(1);
 System.out.println(callerClass.getName());
  • 5 sun.misc.SharedSecrets.getJavaLangAccess
public static void main(String[] args) {
    JavaLangAccess access = sun.misc.SharedSecrets.getJavaLangAccess();
    Throwable throwable = new Throwable();
    int stackTraceDepth = access.getStackTraceDepth(throwable);
    for (int traceDepth = stackTraceDepth-1; traceDepth >=0; traceDepth--) {
        System.out.println( access.getStackTraceElement(throwable, traceDepth).getClassName());
    }
  }

https://stackoverflow.com/questions/23808803/sun-reflect-reflection-getcallerclass-alternative

https://stackoverflow.com/questions/421280/how-do-i-find-the-caller-of-a-method-using-stacktrace-or-reflection

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值