本文主要是介绍如何判断这个方法的调用来自dubbo consumer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个是比较好玩的一个问题? 如何判断呢?
- 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
这篇关于如何判断这个方法的调用来自dubbo consumer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!