Dubbo源码学习--SPI实现@SPI和@Adaptive

1,152 阅读11分钟
原文链接: blog.csdn.net

上一篇博客 Dubbo入门学习--Dubbo服务提供接口SPI机制我们已经简单介绍了Dubbo的SPI机制,这篇博客我们来剖析一下Dubbo是如何使用SPI机制的,在接口中使用@SPI("值")使用默认的实现类,如果我们不想使用默认的实现类是如何处理的。

1、获取指定实现类

在ExtensionLoader中获取默认实现类或者通过实现类名称来获取实现类。

[java] view plain copy print?
  1. Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getDefaultExtension();  
  2. Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("dubbo");  
Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getDefaultExtension();
Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("dubbo");
这样获取的都是实现类DubboProtocol,在之前一篇博客中我们已经了解到,实现类的对应关系是配置在文件中的,从ExtensionLoader会解析文件将数据添加到一个Map中,这样可以直接通过“dubbo”来获取到实现类DubboProtocol。这种实现还是比较简单,但有一个问题就是需要在代码中写死使用哪个实现类,这个就和SPI的初衷有所差别了,因此Dubbo提供了一个另外一个注解@@Adaptive。
2、获取适配器类

Dubbo通过注解@Adaptive作为标记实现了一个适配器类,并且这个类是动态生成的,因此在Dubbo的源码中是看不到代码的,但是我们还是可以看到其实现方式的。Dubbo提供一个动态的适配器类的原因就是可以通过配置文件来动态的使用想要的接口实现类,并且不用改变任何接口的代码,简单来说其也是通过代理来实现的。

[java] view plain copy print?
  1. @SPI("dubbo")  
  2. public interface Protocol {  
  3.       
  4.     int getDefaultPort();  
  5.     
  6.     @Adaptive  
  7.     <T> Exporter<T> export(Invoker<T> invoker) throws RpcException;  
  8.      
  9.     @Adaptive  
  10.     <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;  
  11.   
  12.     void destroy();  
  13.   
  14. }  
@SPI("dubbo")
public interface Protocol {
    
    int getDefaultPort();
  
    @Adaptive
    <T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
   
    @Adaptive
    <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;

    void destroy();

}
在接口Protocol的两个方法export和refer方法中都添加了注解@Adaptive,我们可以认为这两个接口方法会被代理实现。

ExtensionLoader提供了接口获取代理类的方法:

[java] view plain copy print?
  1. Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();  
Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();

1、getAdaptiveExtension首先尝试从缓存中获取实例,如果不存在则创建一个新的实例

[java] view plain copy print?
  1. @SuppressWarnings("unchecked")  
  2.     public T getAdaptiveExtension() {  
  3.         Object instance = cachedAdaptiveInstance.get();  
  4.         if (instance == null) {  
  5.             if(createAdaptiveInstanceError == null) {  
  6.                 synchronized (cachedAdaptiveInstance) {  
  7.                     instance = cachedAdaptiveInstance.get();  
  8.                     if (instance == null) {  
  9.                         try {  
  10.                             //创建代理类  
  11.                             instance = createAdaptiveExtension();  
  12.                             cachedAdaptiveInstance.set(instance);  
  13.                         } catch (Throwable t) {  
  14.                             createAdaptiveInstanceError = t;  
  15.                             throw  new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);  
  16.                         }  
  17.                     }  
  18.                 }  
  19.             }  
  20.             else {  
  21.                 throw new IllegalStateException( "fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);  
  22.             }  
  23.         }  
  24.   
  25.         return (T) instance;  
  26.     }  
@SuppressWarnings("unchecked")
    public T getAdaptiveExtension() {
        Object instance = cachedAdaptiveInstance.get();
        if (instance == null) {
            if(createAdaptiveInstanceError == null) {
                synchronized (cachedAdaptiveInstance) {
                    instance = cachedAdaptiveInstance.get();
                    if (instance == null) {
                        try {
							//创建代理类
                            instance = createAdaptiveExtension();
                            cachedAdaptiveInstance.set(instance);
                        } catch (Throwable t) {
                            createAdaptiveInstanceError = t;
                            throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
                        }
                    }
                }
            }
            else {
                throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
            }
        }

        return (T) instance;
    }

2、createAdaptiveExtension获取一个对象在初始化
[java] view plain copy print?
  1. @SuppressWarnings("unchecked")  
  2.    private T createAdaptiveExtension() {  
  3.        try {  
  4.            return injectExtension((T) getAdaptiveExtensionClass().newInstance());  
  5.        } catch (Exception e) {  
  6.            throw new IllegalStateException("Can not create adaptive extenstion " + type +  ", cause: " + e.getMessage(), e);  
  7.        }  
  8.    }  
 @SuppressWarnings("unchecked")
    private T createAdaptiveExtension() {
        try {
            return injectExtension((T) getAdaptiveExtensionClass().newInstance());
        } catch (Exception e) {
            throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
        }
    }
3、getAdaptiveExtensionClass获取类对象
[java] view plain copy print?
  1. private Class<?> getAdaptiveExtensionClass() {  
  2.       getExtensionClasses();  
  3.       if (cachedAdaptiveClass != null) {  
  4.           return cachedAdaptiveClass;  
  5.       }  
  6.       return cachedAdaptiveClass = createAdaptiveExtensionClass();  
  7.   }  
  private Class<?> getAdaptiveExtensionClass() {
        getExtensionClasses();
        if (cachedAdaptiveClass != null) {
            return cachedAdaptiveClass;
        }
        return cachedAdaptiveClass = createAdaptiveExtensionClass();
    }
4、createAdaptiveExtensionClass中首先会获取代理类的源码,然后在编译源码获取一个Class [java] view plain copy print?
  1. private Class<?> createAdaptiveExtensionClass() {  
  2. //获取一个字符串源码  
  3.       String code = createAdaptiveExtensionClassCode();  
  4.       ClassLoader classLoader = findClassLoader();  
  5.       com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();  
  6. //编译生成代理类  
  7.       return compiler.compile(code, classLoader);  
  8.   }  
  private Class<?> createAdaptiveExtensionClass() {
		//获取一个字符串源码
        String code = createAdaptiveExtensionClassCode();
        ClassLoader classLoader = findClassLoader();
        com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
		//编译生成代理类
        return compiler.compile(code, classLoader);
    }

5、Dubbo实现一个适配器类的关键在createAdaptiveExtensionClassCode,会生成一个类的代理适配器类的源码 [java] view plain copy print?
  1. //生成一个类的代理类源码  
  2.  private String createAdaptiveExtensionClassCode() {  
  3.         StringBuilder codeBuidler = new StringBuilder();  
  4.         Method[] methods = type.getMethods();  
  5.         boolean hasAdaptiveAnnotation = false;  
  6.         for(Method m : methods) {  
  7.             if(m.isAnnotationPresent(Adaptive.class)) {  
  8.                 hasAdaptiveAnnotation = true;  
  9.                 break;  
  10.             }  
  11.         }  
  12.         // 完全没有Adaptive方法,则不需要生成Adaptive类  
  13.         if(! hasAdaptiveAnnotation)  
  14.             throw new IllegalStateException("No adaptive method on extension " + type.getName() +  ", refuse to create the adaptive class!");  
  15.           
  16.         codeBuidler.append("package " + type.getPackage().getName() + ";");  
  17.         codeBuidler.append("\nimport " + ExtensionLoader.class.getName() +  ";");  
  18.         codeBuidler.append("\npublic class " + type.getSimpleName() + "$Adpative" +  " implements " + type.getCanonicalName() + " {");  
  19.           
  20.         for (Method method : methods) {  
  21.             Class<?> rt = method.getReturnType();  
  22.             Class<?>[] pts = method.getParameterTypes();  
  23.             Class<?>[] ets = method.getExceptionTypes();  
  24.   
  25.             Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);  
  26.             StringBuilder code = new StringBuilder(512);  
  27.             if (adaptiveAnnotation == null) {  
  28.                 code.append("throw new UnsupportedOperationException(\"method ")  
  29.                         .append(method.toString()).append(" of interface ")  
  30.                         .append(type.getName()).append(" is not adaptive method!\");");  
  31.             } else {  
  32.                 int urlTypeIndex = -1;  
  33.                 for (int i =  0; i < pts.length; ++i) {  
  34.                     if (pts[i].equals(URL.class)) {  
  35.                         urlTypeIndex = i;  
  36.                         break;  
  37.                     }  
  38.                 }  
  39.                 // 有类型为URL的参数  
  40.                 if (urlTypeIndex != -1) {  
  41.                     // Null Point check  
  42.                     String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");",  
  43.                                     urlTypeIndex);  
  44.                     code.append(s);  
  45.                       
  46.                     s = String.format("\n%s url = arg%d;", URL. class.getName(), urlTypeIndex);   
  47.                     code.append(s);  
  48.                 }  
  49.                 // 参数没有URL类型  
  50.                 else {  
  51.                     String attribMethod = null;  
  52.                       
  53.                     // 找到参数的URL属性  
  54.                     LBL_PTS:  
  55.                     for (int i =  0; i < pts.length; ++i) {  
  56.                         Method[] ms = pts[i].getMethods();  
  57.                         for (Method m : ms) {  
  58.                             String name = m.getName();  
  59.                             if ((name.startsWith( "get") || name.length() > 3)  
  60.                                     && Modifier.isPublic(m.getModifiers())  
  61.                                     && !Modifier.isStatic(m.getModifiers())  
  62.                                     && m.getParameterTypes().length == 0  
  63.                                     && m.getReturnType() == URL.class) {  
  64.                                 urlTypeIndex = i;  
  65.                                 attribMethod = name;  
  66.                                 break LBL_PTS;  
  67.                             }  
  68.                         }  
  69.                     }  
  70.                     if(attribMethod ==  null) {  
  71.                         throw  new IllegalStateException("fail to create adative class for interface " + type.getName()  
  72.                                 + ": not found url parameter or url attribute in parameters of method " + method.getName());  
  73.                     }  
  74.                       
  75.                     // Null point check  
  76.                     String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");",  
  77.                                     urlTypeIndex, pts[urlTypeIndex].getName());  
  78.                     code.append(s);  
  79.                     s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");",  
  80.                                     urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod);  
  81.                     code.append(s);  
  82.   
  83.                     s = String.format("%s url = arg%d.%s();",URL. class.getName(), urlTypeIndex, attribMethod);   
  84.                     code.append(s);  
  85.                 }  
  86.                   
  87.                 String[] value = adaptiveAnnotation.value();  
  88.                 // 没有设置Key,则使用“扩展点接口名的点分隔 作为Key  
  89.                 if(value.length ==  0) {  
  90.                     char[] charArray = type.getSimpleName().toCharArray();  
  91.                     StringBuilder sb = new StringBuilder( 128);  
  92.                     for ( int i = 0; i < charArray.length; i++) {  
  93.                         if(Character.isUpperCase(charArray[i])) {  
  94.                             if(i !=  0) {  
  95.                                 sb.append(".");  
  96.                             }  
  97.                             sb.append(Character.toLowerCase(charArray[i]));  
  98.                         }  
  99.                         else {  
  100.                             sb.append(charArray[i]);  
  101.                         }  
  102.                     }  
  103.                     value = new String[] {sb.toString()};  
  104.                 }  
  105.                   
  106.                 boolean hasInvocation =  false;  
  107.                 for ( int i = 0; i < pts.length; ++i) {  
  108.                     if (pts[i].getName().equals( "com.alibaba.dubbo.rpc.Invocation")) {  
  109.                         // Null Point check  
  110.                         String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i);  
  111.                         code.append(s);  
  112.                         s = String.format("\nString methodName = arg%d.getMethodName();", i);   
  113.                         code.append(s);  
  114.                         hasInvocation = true;  
  115.                         break;  
  116.                     }  
  117.                 }  
  118.                   
  119.                 String defaultExtName = cachedDefaultName;  
  120.                 String getNameCode = null;  
  121.                 for ( int i = value.length - 1; i >=  0; --i) {  
  122.                     if(i == value.length -  1) {  
  123.                         if( null != defaultExtName) {  
  124.                             if(! "protocol".equals(value[i]))  
  125.                                 if (hasInvocation)   
  126.                                     getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);  
  127.                                 else  
  128.                                     getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName);  
  129.                             else  
  130.                                 getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName);  
  131.                         }  
  132.                         else {  
  133.                             if(! "protocol".equals(value[i]))  
  134.                                 if (hasInvocation)   
  135.                                     getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);  
  136.                                 else  
  137.                                     getNameCode = String.format("url.getParameter(\"%s\")", value[i]);  
  138.                             else  
  139.                                 getNameCode = "url.getProtocol()";  
  140.                         }  
  141.                     }  
  142.                     else {  
  143.                         if(! "protocol".equals(value[i]))  
  144.                             if (hasInvocation)   
  145.                                 getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);  
  146.                             else  
  147.                                 getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);  
  148.                         else  
  149.                             getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);  
  150.                     }  
  151.                 }  
  152.                 code.append("\nString extName = ").append(getNameCode).append( ";");  
  153.                 // check extName == null?  
  154.                 String s = String.format("\nif(extName == null) " +  
  155.                         "throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");",  
  156.                         type.getName(), Arrays.toString(value));  
  157.                 code.append(s);  
  158.                   
  159.                 s = String.format("\n%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);",  
  160.                         type.getName(), ExtensionLoader.class.getSimpleName(), type.getName());  
  161.                 code.append(s);  
  162.                   
  163.                 // return statement  
  164.                 if (!rt.equals( void.class)) {  
  165.                     code.append("\nreturn ");  
  166.                 }  
  167.   
  168.                 s = String.format("extension.%s(", method.getName());  
  169.                 code.append(s);  
  170.                 for ( int i =  0; i < pts.length; i++) {  
  171.                     if (i !=  0)  
  172.                         code.append(", ");  
  173.                     code.append("arg").append(i);  
  174.                 }  
  175.                 code.append(");");  
  176.             }  
  177.               
  178.             codeBuidler.append("\npublic " + rt.getCanonicalName() +  " " + method.getName() +  "(");  
  179.             for ( int i =  0; i < pts.length; i ++) {  
  180.                 if (i >  0) {  
  181.                     codeBuidler.append(", ");  
  182.                 }  
  183.                 codeBuidler.append(pts[i].getCanonicalName());  
  184.                 codeBuidler.append(" ");  
  185.                 codeBuidler.append("arg" + i);  
  186.             }  
  187.             codeBuidler.append(")");  
  188.             if (ets.length >  0) {  
  189.                 codeBuidler.append(" throws ");  
  190.                 for ( int i =  0; i < ets.length; i ++) {  
  191.                     if (i >  0) {  
  192.                         codeBuidler.append(", ");  
  193.                     }  
  194.                     codeBuidler.append(ets[i].getCanonicalName());  
  195.                 }  
  196.             }  
  197.             codeBuidler.append(" {");  
  198.             codeBuidler.append(code.toString());  
  199.             codeBuidler.append("\n}");  
  200.         }  
  201.         codeBuidler.append("\n}");  
  202.         if (logger.isDebugEnabled()) {  
  203.             logger.debug(codeBuidler.toString());  
  204.         }  
  205.         return codeBuidler.toString();  
  206.     }  
//生成一个类的代理类源码
 private String createAdaptiveExtensionClassCode() {
        StringBuilder codeBuidler = new StringBuilder();
        Method[] methods = type.getMethods();
        boolean hasAdaptiveAnnotation = false;
        for(Method m : methods) {
            if(m.isAnnotationPresent(Adaptive.class)) {
                hasAdaptiveAnnotation = true;
                break;
            }
        }
        // 完全没有Adaptive方法,则不需要生成Adaptive类
        if(! hasAdaptiveAnnotation)
            throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!");
        
        codeBuidler.append("package " + type.getPackage().getName() + ";");
        codeBuidler.append("\nimport " + ExtensionLoader.class.getName() + ";");
        codeBuidler.append("\npublic class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {");
        
        for (Method method : methods) {
            Class<?> rt = method.getReturnType();
            Class<?>[] pts = method.getParameterTypes();
            Class<?>[] ets = method.getExceptionTypes();

            Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);
            StringBuilder code = new StringBuilder(512);
            if (adaptiveAnnotation == null) {
                code.append("throw new UnsupportedOperationException(\"method ")
                        .append(method.toString()).append(" of interface ")
                        .append(type.getName()).append(" is not adaptive method!\");");
            } else {
                int urlTypeIndex = -1;
                for (int i = 0; i < pts.length; ++i) {
                    if (pts[i].equals(URL.class)) {
                        urlTypeIndex = i;
                        break;
                    }
                }
                // 有类型为URL的参数
                if (urlTypeIndex != -1) {
                    // Null Point check
                    String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");",
                                    urlTypeIndex);
                    code.append(s);
                    
                    s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex); 
                    code.append(s);
                }
                // 参数没有URL类型
                else {
                    String attribMethod = null;
                    
                    // 找到参数的URL属性
                    LBL_PTS:
                    for (int i = 0; i < pts.length; ++i) {
                        Method[] ms = pts[i].getMethods();
                        for (Method m : ms) {
                            String name = m.getName();
                            if ((name.startsWith("get") || name.length() > 3)
                                    && Modifier.isPublic(m.getModifiers())
                                    && !Modifier.isStatic(m.getModifiers())
                                    && m.getParameterTypes().length == 0
                                    && m.getReturnType() == URL.class) {
                                urlTypeIndex = i;
                                attribMethod = name;
                                break LBL_PTS;
                            }
                        }
                    }
                    if(attribMethod == null) {
                        throw new IllegalStateException("fail to create adative class for interface " + type.getName()
                        		+ ": not found url parameter or url attribute in parameters of method " + method.getName());
                    }
                    
                    // Null point check
                    String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");",
                                    urlTypeIndex, pts[urlTypeIndex].getName());
                    code.append(s);
                    s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");",
                                    urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod);
                    code.append(s);

                    s = String.format("%s url = arg%d.%s();",URL.class.getName(), urlTypeIndex, attribMethod); 
                    code.append(s);
                }
                
                String[] value = adaptiveAnnotation.value();
                // 没有设置Key,则使用“扩展点接口名的点分隔 作为Key
                if(value.length == 0) {
                    char[] charArray = type.getSimpleName().toCharArray();
                    StringBuilder sb = new StringBuilder(128);
                    for (int i = 0; i < charArray.length; i++) {
                        if(Character.isUpperCase(charArray[i])) {
                            if(i != 0) {
                                sb.append(".");
                            }
                            sb.append(Character.toLowerCase(charArray[i]));
                        }
                        else {
                            sb.append(charArray[i]);
                        }
                    }
                    value = new String[] {sb.toString()};
                }
                
                boolean hasInvocation = false;
                for (int i = 0; i < pts.length; ++i) {
                    if (pts[i].getName().equals("com.alibaba.dubbo.rpc.Invocation")) {
                        // Null Point check
                        String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i);
                        code.append(s);
                        s = String.format("\nString methodName = arg%d.getMethodName();", i); 
                        code.append(s);
                        hasInvocation = true;
                        break;
                    }
                }
                
                String defaultExtName = cachedDefaultName;
                String getNameCode = null;
                for (int i = value.length - 1; i >= 0; --i) {
                    if(i == value.length - 1) {
                        if(null != defaultExtName) {
                            if(!"protocol".equals(value[i]))
                                if (hasInvocation) 
                                    getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
                                else
                                    getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName);
                            else
                                getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName);
                        }
                        else {
                            if(!"protocol".equals(value[i]))
                                if (hasInvocation) 
                                    getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
                                else
                                    getNameCode = String.format("url.getParameter(\"%s\")", value[i]);
                            else
                                getNameCode = "url.getProtocol()";
                        }
                    }
                    else {
                        if(!"protocol".equals(value[i]))
                            if (hasInvocation) 
                                getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
                            else
                                getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);
                        else
                            getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);
                    }
                }
                code.append("\nString extName = ").append(getNameCode).append(";");
                // check extName == null?
                String s = String.format("\nif(extName == null) " +
                		"throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");",
                        type.getName(), Arrays.toString(value));
                code.append(s);
                
                s = String.format("\n%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);",
                        type.getName(), ExtensionLoader.class.getSimpleName(), type.getName());
                code.append(s);
                
                // return statement
                if (!rt.equals(void.class)) {
                    code.append("\nreturn ");
                }

                s = String.format("extension.%s(", method.getName());
                code.append(s);
                for (int i = 0; i < pts.length; i++) {
                    if (i != 0)
                        code.append(", ");
                    code.append("arg").append(i);
                }
                code.append(");");
            }
            
            codeBuidler.append("\npublic " + rt.getCanonicalName() + " " + method.getName() + "(");
            for (int i = 0; i < pts.length; i ++) {
                if (i > 0) {
                    codeBuidler.append(", ");
                }
                codeBuidler.append(pts[i].getCanonicalName());
                codeBuidler.append(" ");
                codeBuidler.append("arg" + i);
            }
            codeBuidler.append(")");
            if (ets.length > 0) {
                codeBuidler.append(" throws ");
                for (int i = 0; i < ets.length; i ++) {
                    if (i > 0) {
                        codeBuidler.append(", ");
                    }
                    codeBuidler.append(ets[i].getCanonicalName());
                }
            }
            codeBuidler.append(" {");
            codeBuidler.append(code.toString());
            codeBuidler.append("\n}");
        }
        codeBuidler.append("\n}");
        if (logger.isDebugEnabled()) {
            logger.debug(codeBuidler.toString());
        }
        return codeBuidler.toString();
    }

Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();  生成的代理适配器类的源码如下: [java] view plain copy print?
  1. package com.alibaba.dubbo.rpc;  
  2. import com.alibaba.dubbo.common.extension.ExtensionLoader;  
  3. public class Protocol$Adpative implements com.alibaba.dubbo.rpc.Protocol {  
  4.     public void destroy() {  
  5.         throw new UnsupportedOperationException("method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");  
  6.     }  
  7.     public int getDefaultPort() {  
  8.         throw new UnsupportedOperationException("method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");  
  9.     }  
  10.     public com.alibaba.dubbo.rpc.Exporter (com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.RpcException {  
  11.         if (arg0 == null) throw  new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null");  
  12.         if (arg0.getUrl() == null) throw  new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null");com.alibaba.dubbo.common.URL url = arg0.getUrl();  
  13.         String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );  
  14.         if(extName == null) throw  new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() +  ") use keys([protocol])");  
  15.         com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);  
  16.         return extension.export(arg0);  
  17.     }  
  18.     public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {  
  19.         if (arg1 == null) throw  new IllegalArgumentException("url == null");  
  20.         com.alibaba.dubbo.common.URL url = arg1;  
  21.         String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );  
  22.         if(extName == null) throw  new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() +  ") use keys([protocol])");  
  23.         com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);  
  24.         return extension.refer(arg0, arg1);  
  25.     }  
  26. }  
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adpative implements com.alibaba.dubbo.rpc.Protocol {
	public void destroy() {
		throw new UnsupportedOperationException("method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
	}
	public int getDefaultPort() {
		throw new UnsupportedOperationException("method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
	}
	public com.alibaba.dubbo.rpc.Exporter (com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.RpcException {
		if (arg0 == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null");
		if (arg0.getUrl() == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null");com.alibaba.dubbo.common.URL url = arg0.getUrl();
		String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
		if(extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
		com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
		return extension.export(arg0);
	}
	public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {
		if (arg1 == null) throw new IllegalArgumentException("url == null");
		com.alibaba.dubbo.common.URL url = arg1;
		String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
		if(extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
		com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
		return extension.refer(arg0, arg1);
	}
}

我们分析一下,生成的代理器类如果被调用refer方法时会发生的处理操作,简单来说是通过代理方式来生成一个适配器类。 [java] view plain copy print?
  1. public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {  
  2.         if (arg1 == null) throw  new IllegalArgumentException("url == null");  
  3.         //被Adattive注解的方法中有个参数必须是URL对象或者参数可以通过getUrl()获取到一个url不然会抛出异常  
  4.         com.alibaba.dubbo.common.URL url = arg1;  
  5.         //首先会判断url中是否指定了协议,不然使用默认  
  6.         String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );  
  7.         if(extName == null) throw  new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() +  ") use keys([protocol])");  
  8.         //获取实现类  
  9.         com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);  
  10.         //最终调用实现类的refer方法  
  11.         return extension.refer(arg0, arg1);  
  12.     }  
public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {
		if (arg1 == null) throw new IllegalArgumentException("url == null");
		//被Adattive注解的方法中有个参数必须是URL对象或者参数可以通过getUrl()获取到一个url不然会抛出异常
		com.alibaba.dubbo.common.URL url = arg1;
		//首先会判断url中是否指定了协议,不然使用默认
		String extName = ( url.getProtocol() == null ? "dubbo" : url.getProtocol() );
		if(extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
		//获取实现类
		com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol)ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
		//最终调用实现类的refer方法
		return extension.refer(arg0, arg1);
	}


总结:Dubbo通过两个注解SPI和Adaptive,通过参数中URL.getProtocol可以动态的使用各种实现类。