Extension Point Development Guide

This article introduces the principles and implementation details of Dubbo SPI.

1. Introduction to Dubbo SPI Extensions

The extension mechanism in Dubbo is similar to the JDK standard SPI extension points principle. Dubbo has made certain modifications and enhancements:

  • The JDK standard SPI instantiates all extension point implementations at once, which can waste resources if the extension implementations are resource-intensive but not used.
  • If an extension point fails to load, JDK SPI does not provide detailed information to locate the problem, while Dubbo SPI logs the actual failure reason on failure and prints it out.
  • Adds IOC, AOP capabilities.
  • Adds sorting capabilities.
  • Adds conditional activation capabilities.
  • Provides a series of more flexible APIs, such as getting all SPI extension implementations, querying a specific extension implementation by name, querying extensions by type, and querying extension implementations that match conditions.

1.1 Definition of SPI

The SPI plugin in Dubbo is standard Java Interface definition and must contain the @org.apache.dubbo.common.extension.SPI annotation:

  1. @SPI(value = "dubbo", scope = ExtensionScope.FRAMEWORK)
  2. public interface Protocol {
  3. // ...
  4. }

The definition of the @SPI annotation is as follows:

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target({ElementType.TYPE})
  4. public @interface SPI {
  5. /**
  6. * Default extension name
  7. */
  8. String value() default "";
  9. /**
  10. * Scope of SPI, default value is application scope.
  11. */
  12. ExtensionScope scope() default ExtensionScope.APPLICATION;
  13. }

1.2 SPI Loading Process

The whole process of Dubbo loading extensions is as follows:

//imgs/v3/concepts/extension-load.png

The main steps are 4:

  • Read and parse configuration files.
  • Cache all extension implementations.
  • Instantiate the corresponding extension implementation based on the extension name executed by the user.
  • Perform IOC injection for extension instance properties and instantiate wrapper classes for extensions to implement AOP features.

2. Source Code Analysis of Dubbo SPI

2.1 Getting a Specific Extension Class by Name

In Dubbo, the entry for loading fixed extension classes is the getExtension method of ExtensionLoader. Below, we analyze the acquisition process of the extension class object in detail.

  1. public T getExtension(String name) {
  2. if (name == null || name.length() == 0)
  3. throw new IllegalArgumentException("Extension name == null");
  4. if ("true".equals(name)) {
  5. // Get the default extension implementation class
  6. return getDefaultExtension();
  7. }
  8. // Holder, as the name suggests, is used to hold the target object
  9. Holder<Object> holder = cachedInstances.get(name);
  10. // This logic ensures that only one thread can create the Holder object
  11. if (holder == null) {
  12. cachedInstances.putIfAbsent(name, new Holder<Object>());
  13. holder = cachedInstances.get(name);
  14. }
  15. Object instance = holder.get();
  16. // Double-check
  17. if (instance == null) {
  18. synchronized (holder) {
  19. instance = holder.get();
  20. if (instance == null) {
  21. // Create extension instance
  22. instance = createExtension(name);
  23. // Set instance in holder
  24. holder.set(instance);
  25. }
  26. }
  27. }
  28. return (T) instance;
  29. }

The logic of the code above is quite straightforward; it first checks the cache, and if it doesn’t hit the cache, it creates the extension object. Next, let’s look at the process of creating the extension object.

  1. private T createExtension(String name, boolean wrap) {
  2. // Load all extension classes from the configuration file, which can obtain the "configuration item name" to "configuration class" mapping table
  3. Class<?> clazz = getExtensionClasses().get(name);
  4. // If there is no extension for the interface, or the implementation class of the interface does not allow duplication but actually duplicates, throw an exception directly
  5. if (clazz == null || unacceptableExceptions.contains(name)) {
  6. throw findException(name);
  7. }
  8. try {
  9. T instance = (T) EXTENSION_INSTANCES.get(clazz);
  10. // This code ensures that the extension class is constructed only once, meaning it's a singleton.
  11. if (instance == null) {
  12. EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.getDeclaredConstructor().newInstance());
  13. instance = (T) EXTENSION_INSTANCES.get(clazz);
  14. }
  15. // Inject dependencies into the instance
  16. injectExtension(instance);
  17. // If wrapping is enabled, automatically wrap it.
  18. // For example, I defined the extension of DubboProtocol based on Protocol, but in Dubbo, it's not directly used as DubboProtocol; rather, it's used as its wrapper class
  19. // ProtocolListenerWrapper
  20. if (wrap) {
  21. List<Class<?>> wrapperClassesList = new ArrayList<>();
  22. if (cachedWrapperClasses != null) {
  23. wrapperClassesList.addAll(cachedWrapperClasses);
  24. wrapperClassesList.sort(WrapperComparator.COMPARATOR);
  25. Collections.reverse(wrapperClassesList);
  26. }
  27. // Loop to create Wrapper instances
  28. if (CollectionUtils.isNotEmpty(wrapperClassesList)) {
  29. for (Class<?> wrapperClass : wrapperClassesList) {
  30. Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class);
  31. if (wrapper == null
  32. || (ArrayUtils.contains(wrapper.matches(), name) && !ArrayUtils.contains(wrapper.mismatches(), name))) {
  33. // Pass the current instance as a parameter to the Wrapper constructor and create the Wrapper instance through reflection.
  34. // Then inject dependencies into the Wrapper instance, and finally assign the Wrapper instance back to the instance variable
  35. instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
  36. }
  37. }
  38. }
  39. }
  40. // Initialization
  41. initExtension(instance);
  42. return instance;
  43. } catch (Throwable t) {
  44. throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
  45. type + ") couldn't be instantiated: " + t.getMessage(), t);
  46. }
  47. }

The logic of createExtension method is slightly more complex and consists of the following steps:

  1. Load all extension classes through getExtensionClasses.
  2. Create the extension object through reflection.
  3. Inject dependencies into the extension object.
  4. Wrap the extension object in the corresponding Wrapper object.
  5. Initialize the extension object.

Among the above steps, the first step is crucial for loading extension classes, while steps three and four are the specific implementations of Dubbo IOC and AOP. In the following chapters, we will focus on analyzing the logic of the getExtensionClasses method and briefly introduce the specific implementation of Dubbo IOC.

2.1.1 Getting All Extension Classes

Before we get extension classes by name, we first need to parse the configuration file to obtain a mapping table from extension item names to extension classes (Map<Name, Extension Class>), and then extract the corresponding extension class from this mapping table based on the extension item names. The relevant process code analysis is as follows:

  1. private Map<String, Class<?>> getExtensionClasses() {
  2. // Get already loaded extension classes from cache
  3. Map<String, Class<?>> classes = cachedClasses.get();
  4. // Double check
  5. if (classes == null) {
  6. synchronized (cachedClasses) {
  7. classes = cachedClasses.get();
  8. if (classes == null) {
  9. // Load extension classes
  10. classes = loadExtensionClasses();
  11. cachedClasses.set(classes);
  12. }
  13. }
  14. }
  15. return classes;
  16. }

Here, we also check the cache first, and if not found, lock through synchronized. After locking, check the cache again, and if it’s still null, load the extension classes through loadExtensionClasses. Next, we analyze the logic of loadExtensionClasses method.

  1. private Map<String, Class<?>> loadExtensionClasses() {
  2. // Cache default SPI extension name
  3. cacheDefaultExtensionName();
  4. Map<String, Class<?>> extensionClasses = new HashMap<>();
  5. // Load files from the specified folder based on strategies
  6. // Currently, there are four strategies to read configuration files in the directories: META-INF/services/, META-INF/dubbo/, META-INF/dubbo/internal/, META-INF/dubbo/external/
  7. for (LoadingStrategy strategy : strategies) {
  8. loadDirectory(extensionClasses, strategy.directory(), type.getName(), strategy.preferExtensionClassLoader(), strategy.overridden(), strategy.excludedPackages());
  9. loadDirectory(extensionClasses, strategy.directory(), type.getName().replace("org.apache", "com.alibaba"), strategy.preferExtensionClassLoader(), strategy.overridden(), strategy.excludedPackages());
  10. }
  11. return extensionClasses;
  12. }

The loadExtensionClasses method performs two main tasks: parsing the SPI annotation and calling the loadDirectory method to load the specified folder’s configuration files. The SPI annotation parsing process is straightforward and does not require further explanation. Next, let’s look at what loadDirectory does.

  1. private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type,
  2. boolean extensionLoaderClassLoaderFirst, boolean overridden, String... excludedPackages) {
  3. // fileName = folder path + type fully qualified name
  4. String fileName = dir + type;
  5. try {
  6. Enumeration<java.net.URL> urls = null;
  7. ClassLoader classLoader = findClassLoader();
  8. // try to load from ExtensionLoader's ClassLoader first
  9. if (extensionLoaderClassLoaderFirst) {
  10. ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader();
  11. if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) {
  12. urls = extensionLoaderClassLoader.getResources(fileName);
  13. }
  14. }
  15. // Load all files with the same name based on the file name
  16. if (urls == null || !urls.hasMoreElements()) {
  17. if (classLoader != null) {
  18. urls = classLoader.getResources(fileName);
  19. } else {
  20. urls = ClassLoader.getSystemResources(fileName);
  21. }
  22. }
  23. if (urls != null) {
  24. while (urls.hasMoreElements()) {
  25. java.net.URL resourceURL = urls.nextElement();
  26. // Load resources
  27. loadResource(extensionClasses, classLoader, resourceURL, overridden, excludedPackages);
  28. }
  29. }
  30. } catch (Throwable t) {
  31. logger.error("Exception occurred when loading extension class (interface: " +
  32. type + ", description file: " + fileName + ").", t);
  33. }
  34. }

The loadDirectory method first obtains all resource links through classLoader, then loads the resource through the loadResource method. Let’s continue to see the implementation of the loadResource method.

  1. private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader,
  2. java.net.URL resourceURL, boolean overridden, String... excludedPackages) {
  3. try {
  4. try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), StandardCharsets.UTF_8))) {
  5. String line;
  6. String clazz = null;
  7. // Read configuration content line by line
  8. while ((line = reader.readLine()) != null) {
  9. // Locate the # character
  10. final int ci = line.indexOf('#');
  11. if (ci >= 0) {
  12. // Take the substring before the #, and ignore the content after #
  13. line = line.substring(0, ci);
  14. }
  15. line = line.trim();
  16. if (line.length() > 0) {
  17. try {
  18. String name = null;
  19. // Split between key and value based on the equal sign =
  20. int i = line.indexOf('=');
  21. if (i > 0) {
  22. name = line.substring(0, i).trim();
  23. clazz = line.substring(i + 1).trim();
  24. } else {
  25. clazz = line;
  26. }
  27. // Load class and cache it through the loadClass method
  28. if (StringUtils.isNotEmpty(clazz) && !isExcluded(clazz, excludedPackages)) {
  29. loadClass(extensionClasses, resourceURL, Class.forName(clazz, true, classLoader), name, overridden);
  30. }
  31. } catch (Throwable t) {
  32. IllegalStateException e = new IllegalStateException("Failed to load extension class (interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t);
  33. exceptions.put(line, e);
  34. }
  35. }
  36. }
  37. }
  38. } catch (Throwable t) {
  39. logger.error("Exception occurred when loading extension class (interface: " +
  40. type + ", class file: " + resourceURL + ") in " + resourceURL, t);
  41. }
  42. }

The loadResource method reads and parses configuration files, loads classes through reflection, and finally calls the loadClass method for other operations. The loadClass method is primarily used for cache operations, and its logic is as follows:

  1. private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name,
  2. boolean overridden) throws NoSuchMethodException {
  3. if (!type.isAssignableFrom(clazz)) {
  4. throw new IllegalStateException("Error occurred when loading extension class (interface: " +
  5. type + ", class line: " + clazz.getName() + "), class "
  6. + clazz.getName() + " is not subtype of interface.");
  7. }
  8. // Check if the target class has the Adaptive annotation
  9. if (clazz.isAnnotationPresent(Adaptive.class)) {
  10. cacheAdaptiveClass(clazz, overridden);
  11. } else if (isWrapperClass(clazz)) {
  12. // Cache wrapper classes
  13. cacheWrapperClass(clazz);
  14. } else {
  15. // If we reach here, it means the class is just an ordinary extension class
  16. // Check if clazz has a default constructor; if not, throw an exception
  17. clazz.getConstructor();
  18. if (StringUtils.isEmpty(name)) {
  19. // If name is empty, try to get name from the Extension annotation or use lowercase class name as the name
  20. name = findAnnotationName(clazz);
  21. if (name.length() == 0) {
  22. throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL);
  23. }
  24. }
  25. String[] names = NAME_SEPARATOR.split(name);
  26. if (ArrayUtils.isNotEmpty(names)) {
  27. // If there is an Activate annotation on the class, use the first element of the names array as the key,
  28. // store the mapping of name to the Activate annotation object
  29. cacheActivateClass(clazz, names[0]);
  30. for (String n : names) {
  31. // Store Class to name mapping
  32. cacheName(clazz, n);
  33. // Store name to Class mapping.
  34. // If the same extension name corresponds to multiple implementation classes, based on the override parameter whether overrides are allowed,
  35. // if not allowed, throw an exception.
  36. saveInExtensionClass(extensionClasses, clazz, n, overridden);
  37. }
  38. }
  39. }
  40. }

As seen, the loadClass method operates on different caches, such as cachedAdaptiveClass, cachedWrapperClasses, and cachedNames, among others. Apart from this, there aren’t many other logics in the method.

Thus, the process of loading cached classes has been fully analyzed. The entire process is not particularly complex; analyze it step by step, and if there are any unclear parts, you can debug.

2.2 Loading Adaptive Extension Classes

First, let’s explain the scenario of using adaptive extension classes. For example, if we have a demand to select different implementation classes based on parameters when calling a specific method, this is somewhat similar to the factory method, creating different instance objects based on different parameters. The idea implemented in Dubbo is quite similar, but Dubbo’s implementation is more flexible and akin to the strategy pattern. Each extension class essentially represents a strategy, passing parameters to the ExtensionLoader via the URL message bus to load the corresponding extension class based on parameters, achieving dynamic invocation of the target instance at runtime.

The meaning of adaptive extension classes is to dynamically select the specific target class at runtime based on parameters and then execute.

In Dubbo, many extensions are loaded through the SPI mechanism, such as Protocol, Cluster, LoadBalance, etc. Sometimes, some extensions do not wish to be loaded at the framework startup stage, but rather want to be loaded when the extension method is called, based on runtime parameters. This may sound contradictory. If the extension is not loaded, then the extension method cannot be called (except for static methods). If the extension method has not been called, then the extension cannot be loaded. For this contradictory issue, Dubbo solves it well through the adaptive extension mechanism. The implementation logic of the adaptive extension mechanism is fairly complex; first, Dubbo will generate proxy code for the extension interfaces. It then compiles this code using Javassist or JDK, resulting in a Class instance. Finally, it uses reflection to create the proxy class, making the entire process quite complex.

The entry point for loading adaptive extension classes is the getAdaptiveExtension method of ExtensionLoader.

  1. public T getAdaptiveExtension() {
  2. // Get adaptive extension from cache
  3. Object instance = cachedAdaptiveInstance.get();
  4. if (instance == null) {
  5. // If there is an exception, directly throw
  6. if (createAdaptiveInstanceError != null) {
  7. throw new IllegalStateException("Failed to create adaptive instance: " +
  8. createAdaptiveInstanceError.toString(),
  9. createAdaptiveInstanceError);
  10. }
  11. synchronized (cachedAdaptiveInstance) {
  12. instance = cachedAdaptiveInstance.get();
  13. // double check
  14. if (instance == null) {
  15. try {
  16. // Create adaptive extension
  17. // There are two situations: one is having an Adaptive class, and another is needing to generate an Adaptive class
  18. instance = createAdaptiveExtension();
  19. cachedAdaptiveInstance.set(instance);
  20. } catch (Throwable t) {
  21. createAdaptiveInstanceError = t;
  22. throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t);
  23. }
  24. }
  25. }
  26. }
  27. return (T) instance;
  28. }

The getAdaptiveExtension method first checks the cache, and if not hit, it calls the createAdaptiveExtension method to create an adaptive extension. Next, let’s look at the code for the createAdaptiveExtension method.

  1. private T createAdaptiveExtension() {
  2. try {
  3. // Get the adaptive extension class and instantiate it via reflection
  4. return injectExtension((T) getAdaptiveExtensionClass().newInstance());
  5. } catch (Exception e) {
  6. throw new IllegalStateException("Cannot create adaptive extension ...");
  7. }
  8. }

The createAdaptiveExtension method is relatively short but contains three logics as follows:

  1. Call the getAdaptiveExtensionClass method to get the adaptive extension Class object.
  2. Instantiate it via reflection.
  3. Call the injectExtension method to inject dependencies into the extension instance.

The first two logics are easy to understand, while the third logic is to inject dependencies into the adaptive extension object. This logic may seem redundant, but it is necessary. The reason is simple. It has been mentioned earlier that there are two types of adaptive extensions in Dubbo: one is manually coded, and the other is automatically generated. There may be dependencies in the manually coded adaptive extensions, while automatically generated Adaptive extensions will not depend on other classes. The purpose of calling the injectExtension method here is to inject dependencies into manually coded adaptive extensions; this point needs to be noted. Regarding the injectExtension method, it has been analyzed earlier, and there is no need to elaborate further. Next, we will analyze the logic of the getAdaptiveExtensionClass method.

  1. private Class<?> getAdaptiveExtensionClass() {
  2. // Get all extension classes via SPI
  3. getExtensionClasses();
  4. // Check the cache; if not null, return it directly
  5. if (cachedAdaptiveClass != null) {
  6. return cachedAdaptiveClass;
  7. }
  8. // Create the adaptive extension class
  9. return cachedAdaptiveClass = createAdaptiveExtensionClass();
  10. }

The getAdaptiveExtensionClass method also includes three logics, as follows:

  1. Call getExtensionClasses to get all extension classes.
  2. Check the cache; if not null, return it.
  3. If the cache is null, call createAdaptiveExtensionClass to create the adaptive extension class.

These three logics appear plain and may not seem to require much explanation. However, there are some details hidden in these plain codes that need highlighting. Firstly, starting from the first logic, the getExtensionClasses method is used to obtain all implementation classes of a certain interface. For instance, this method can obtain the DubboProtocol, HttpProtocol, InjvmProtocol, etc., implementation classes for the Protocol interface. In the process of retrieving implementation classes, if any implementation class is annotated with Adaptive, that class will be assigned to the cachedAdaptiveClass variable. At this point, the condition for the second step above is satisfied (the cache is not null), and it directly returns cachedAdaptiveClass. If all implementation classes are not annotated with Adaptive, the third-step logic is executed to create the adaptive extension class. The relevant code is as follows:

  1. private Class<?> createAdaptiveExtensionClass() {
  2. // Build the adaptive extension code
  3. String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate();
  4. ClassLoader classLoader = findClassLoader();
  5. // Get the compiler implementation class
  6. org.apache.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
  7. // Compile the code and generate Class
  8. return compiler.compile(code, classLoader);
  9. }

The createAdaptiveExtensionClass method is used to generate adaptive extension classes. This method first generates the source code for the adaptive extension class, then compiles this code using an instance of Compiler (by default, Dubbo uses Javassist as a compiler) to obtain the Class instance for the proxy class. Next, we will focus on the logic for generating the proxy class code; the other logic can be analyzed independently.

2.2.1 Code Generation for Adaptive Extension Classes

AdaptiveClassCodeGenerator#generate method generates the extension class code

  1. public String generate() {
  2. // If there is no method in the interface marked with @Adaptive, throw an exception directly
  3. if (!hasAdaptiveMethod()) {
  4. throw new IllegalStateException("No adaptive method exist on extension " + type.getName() + ", refuse to create the adaptive class!");
  5. }
  6. StringBuilder code = new StringBuilder();
  7. // Generate package name, imports, methods, etc.
  8. code.append(generatePackageInfo());
  9. code.append(generateImports());
  10. code.append(generateClassDeclaration());
  11. Method[] methods = type.getMethods();
  12. for (Method method : methods) {
  13. code.append(generateMethod(method));
  14. }
  15. code.append("}");
  16. if (logger.isDebugEnabled()) {
  17. logger.debug(code.toString());
  18. }
  19. return code.toString();
  20. }

2.2.2 Generate Method

The logic in the method generation part above is most crucial, so we analyze it in detail.

  1. private String generateMethod(Method method) {
  2. String methodReturnType = method.getReturnType().getCanonicalName();
  3. String methodName = method.getName();
  4. // Generate method content
  5. String methodContent = generateMethodContent(method);
  6. String methodArgs = generateMethodArguments(method);
  7. String methodThrows = generateMethodThrows(method);
  8. return String.format(CODE_METHOD_DECLARATION, methodReturnType, methodName, methodArgs, methodThrows, methodContent);
  9. }

Analyzing the generateMethodContent logic

  1. private String generateMethodContent(Method method) {
  2. // The method must have the @Adaptive annotation
  3. Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class);
  4. StringBuilder code = new StringBuilder(512);
  5. if (adaptiveAnnotation == null) {
  6. // Not annotated with @Adaptive, generate exception message
  7. return generateUnsupported(method);
  8. } else {
  9. // Get the index of the URL type in the parameter list
  10. int urlTypeIndex = getUrlTypeIndex(method);
  11. if (urlTypeIndex != -1) {
  12. // If there is a URL in the parameter list, generate a null check for the URL
  13. code.append(generateUrlNullCheck(urlTypeIndex));
  14. } else {
  15. // If there is no URL type parameter in the parameter list, check if the parameter object has a getUrl method
  16. // If yes, generate a URL null check
  17. code.append(generateUrlAssignmentIndirectly(method));
  18. }
  19. // Parse the value attribute from the Adaptive annotation
  20. String[] value = getMethodAdaptiveValue(adaptiveAnnotation);
  21. // If there is an Invocation type parameter in the parameter list, generate a null check and obtain methodName.
  22. boolean hasInvocation = hasInvocationArgument(method);
  23. code.append(generateInvocationArgumentNullCheck(method));
  24. // This logic primarily generates extName (which is the extension name)
  25. // It consists of multiple conditions:
  26. // 1. Whether defaultExtName exists
  27. // 2. Whether there is an invocation type parameter in the parameters
  28. // 3. Whether it is generating a proxy for the protocol
  29. // Why treat the protocol separately? Because the protocol value can be obtained from the URL.
  30. code.append(generateExtNameAssignment(value, hasInvocation));
  31. // check extName == null?
  32. code.append(generateExtNameNullCheck(value));
  33. // Generate obtaining the extension (using ExtensionLoader.getExtension method)
  34. code.append(generateExtensionAssignment());
  35. // Generate return statement
  36. code.append(generateReturnAndInvocation(method));
  37. }
  38. return code.toString();
  39. }

The logic above mainly accomplishes the following tasks:

  1. Check if the method is annotated with Adaptive.
  2. Generate code for the method ensuring the URL is in the parameter list (or in the parameter object).
  3. Use ExtensionLoader.getExtension to get the extension.
  4. Execute the corresponding method.

2.2.3 Example of Code Generated Dynamically

  1. package org.apache.dubbo.common.extension.adaptive;
  2. import org.apache.dubbo.common.extension.ExtensionLoader;
  3. public class HasAdaptiveExt$Adaptive implements org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt {
  4. public java.lang.String echo(org.apache.dubbo.common.URL arg0,
  5. java.lang.String arg1) {
  6. // URL null check
  7. if (arg0 == null) {
  8. throw new IllegalArgumentException("url == null");
  9. }
  10. org.apache.dubbo.common.URL url = arg0;
  11. // Get extension name
  12. String extName = url.getParameter("has.adaptive.ext", "adaptive");
  13. // Extension name null check
  14. if (extName == null) {
  15. throw new IllegalStateException(
  16. "Failed to get extension (org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt) name from url (" +
  17. url.toString() + ") use keys([has.adaptive.ext])");
  18. }
  19. // Get extension
  20. org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt extension = (org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt) ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.extension.adaptive.HasAdaptiveExt.class)
  21. .getExtension(extName);
  22. // Execute corresponding method
  23. return extension.echo(arg0, arg1);
  24. }
  25. }

2.3 IOC Mechanism

Dubbo IOC injects dependencies via setter methods. Firstly, Dubbo will use reflection to obtain all methods of the instance, then traverse the method list to check if the method name features setter methods. If found, it uses ObjectFactory to obtain the dependency object and finally calls the setter method via reflection to set the dependency into the target object. The relevant code for the entire process is as follows:

  1. private T injectExtension(T instance) {
  2. if (objectFactory == null) {
  3. return instance;
  4. }
  5. try {
  6. // Traverse all methods of the target class
  7. for (Method method : instance.getClass().getMethods()) {
  8. // Check if the method starts with set, has a single parameter and is public
  9. if (!isSetter(method)) {
  10. continue;
  11. }
  12. /**
  13. * Check for DisableInject annotation.
  14. */
  15. if (method.getAnnotation(DisableInject.class) != null) {
  16. continue;
  17. }
  18. /**
  19. * Check if it implements ScopeModelAware, ExtensionAccessorAware classes; if so, do not inject.
  20. */
  21. if (method.getDeclaringClass() == ScopeModelAware.class) {
  22. continue;
  23. }
  24. if (instance instanceof ScopeModelAware || instance instanceof ExtensionAccessorAware) {
  25. if (ignoredInjectMethodsDesc.contains(ReflectUtils.getDesc(method))) {
  26. continue;
  27. }
  28. }
  29. // Do not inject for primitive types.
  30. Class<?> pt = method.getParameterTypes()[0];
  31. if (ReflectUtils.isPrimitives(pt)) {
  32. continue;
  33. }
  34. try {
  35. // Obtain property name, for example, setName corresponds to property name name.
  36. String property = getSetterProperty(method);
  37. // Get the dependency object from ObjectFactory.
  38. Object object = objectFactory.getExtension(pt, property);
  39. if (object != null) {
  40. // Inject
  41. method.invoke(instance, object);
  42. }
  43. } catch (Exception e) {
  44. logger.error("Failed to inject via method " + method.getName()
  45. + " of interface " + type.getName() + ": " + e.getMessage(), e);
  46. }
  47. }
  48. } catch (Exception e) {
  49. logger.error(e.getMessage(), e);
  50. }
  51. return instance;
  52. }

In the code above, the objectFactory variable is of type AdaptiveExtensionFactory, which maintains a list of ExtensionFactories to store other types of ExtensionFactories. There are currently two types of ExtensionFactory provided, namely SpiExtensionFactory and SpringExtensionFactory. The former is used to create adaptive extensions, while the latter is used to get the required extensions from the Spring IOC container. The code for these two classes is not particularly complex, so there is no need for detailed analysis.

Dubbo IOC currently only supports setter-based injection, and overall, the logic is relatively simple and easy to understand.

2.4 AOP Mechanism

The Dubbo AOP mechanism is implemented using the wrapper design pattern. To become an AOP wrapper class, it must satisfy the following three conditions:

  1. The wrapper class must implement the SPI interface, such as class QosProtocolWrapper implements Protocol in the example below.
  2. The constructor must include a same SPI parameter, such as QosProtocolWrapper(Protocol protocol) in the example below.
  3. The wrapper class must be written to the configuration file just like ordinary SPI implementations, such as resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol.
  1. public class QosProtocolWrapper implements Protocol, ScopeModelAware {
  2. private final Protocol protocol;
  3. public QosProtocolWrapper(Protocol protocol) {
  4. if (protocol == null) {
  5. throw new IllegalArgumentException("protocol == null");
  6. }
  7. this.protocol = protocol;
  8. }
  9. }

In the configuration file resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol, it is written as follows:

  1. qos=org.apache.dubbo.qos.protocol.QosProtocolWrapper

When attempting to obtain and load SPI extension instances through getExtension(name), the Dubbo framework will determine all wrapper class implementations that meet the above three conditions and wrap the wrapper class around the instance in sequence, thus achieving the effect of AOP interception.

Here is the implementation logic for wrapper determination and loading; you can also use the @Wrapper annotation to control the activation conditions of the wrapper class:

  1. private T createExtension(String name, boolean wrap) {
  2. Class<?> clazz = getExtensionClasses().get(name);
  3. T instance = (T) extensionInstances.get(clazz);
  4. // ...
  5. if (wrap) { // If the caller indicates that AOP is needed, i.e., wrap=true
  6. List<Class<?>> wrapperClassesList = new ArrayList<>();
  7. if (cachedWrapperClasses != null) {
  8. wrapperClassesList.addAll(cachedWrapperClasses);
  9. wrapperClassesList.sort(WrapperComparator.COMPARATOR);
  10. Collections.reverse(wrapperClassesList);
  11. }
  12. if (CollectionUtils.isNotEmpty(wrapperClassesList)) {
  13. for (Class<?> wrapperClass : wrapperClassesList) {
  14. // Use @Wrapper annotation to determine whether the current wrapper class should take effect
  15. Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class);
  16. boolean match = (wrapper == null)
  17. || ((ArrayUtils.isEmpty(wrapper.matches())
  18. || ArrayUtils.contains(wrapper.matches(), name))
  19. && !ArrayUtils.contains(wrapper.mismatches(), name));
  20. if (match) {
  21. instance = injectExtension(
  22. (T) wrapperClass.getConstructor(type).newInstance(instance));
  23. instance = postProcessAfterInitialization(instance, name);
  24. }
  25. }
  26. }
  27. }
  28. }

2.5 Activate Activation Conditions

You can use @org.apache.dubbo.common.extension.Activate to control the circumstances under which SPI extension implementations are loaded and take effect. Compared to being active in all scenarios, being able to precisely control the activation conditions for the extension implementations will make implementations more flexible.

Here are some usage scenario examples:

  1. // Without @Activate annotation, it won't load during getActivateExtension(), other getExtension() methods can still load normally.
  2. public class MetricsProviderFilter implements Filter{}
  1. // Without any parameters, indicating unconditional automatic return during getActivateExtension().
  2. @Activate
  3. public class MetricsProviderFilter implements Filter{}
  1. // group supports two fixed values: consumer and provider, automatically filters during loading extensions when calling getActivateExtension()
  2. // provider indicates it will be loaded on the provider side; consumer indicates it will be loaded on the consumer side.
  3. @Activate(group="provider")
  4. public class MetricsProviderFilter implements Filter{}
  1. // Will only load when the URL parameter contains the key cache during getActivateExtension().
  2. @Activate(value="cache")
  3. public class MetricsProviderFilter implements Filter{}
  1. // Will only load when the URL parameter contains the key cache and its value is test during getActivateExtension().
  2. @Activate(value="cache:test")
  3. public class MetricsProviderFilter implements Filter{}

Here is the specific definition of the @Activate annotation:

  1. /**
  2. * Activate. This annotation is useful for automatically activate certain extensions with the given criteria,
  3. * for examples: <code>@Activate</code> can be used to load certain <code>Filter</code> extension when there are
  4. * multiple implementations.
  5. * <ol>
  6. * <li>{@link Activate#group()} specifies group criteria. Framework SPI defines the valid group values.
  7. * <li>{@link Activate#value()} specifies parameter key in {@link URL} criteria.
  8. * </ol>
  9. * SPI provider can call {@link ExtensionLoader#getActivateExtension(URL, String, String)} to find out all activated
  10. * extensions with the given criteria.
  11. *
  12. */
  13. @Documented
  14. @Retention(RetentionPolicy.RUNTIME)
  15. @Target({ElementType.TYPE, ElementType.METHOD})
  16. public @interface Activate {
  17. /**
  18. * Activate the current extension when one of the groups matches. The group passed into
  19. * {@link ExtensionLoader#getActivateExtension(URL, String, String)} will be used for matching.
  20. *
  21. * @return group names to match
  22. * @see ExtensionLoader#getActivateExtension(URL, String, String)
  23. */
  24. String[] group() default {};
  25. /**
  26. * Activate the current extension when the specified keys appear in the URL's parameters.
  27. * <p>
  28. * For example, given <code>@Activate("cache, validation")</code>, the current extension will be return only when
  29. * there's either <code>cache</code> or <code>validation</code> key appeared in the URL's parameters.
  30. * </p>
  31. *
  32. * @return URL parameter keys
  33. * @see ExtensionLoader#getActivateExtension(URL, String)
  34. * @see ExtensionLoader#getActivateExtension(URL, String, String)
  35. */
  36. String[] value() default {};
  37. /**
  38. * Absolute ordering info, optional
  39. *
  40. * Ascending order, smaller values will be in the front o the list.
  41. *
  42. * @return absolute ordering info
  43. */
  44. int order() default 0;
  45. /**
  46. * Activate loadClass when the current extension when the specified className all match
  47. * @return className names to all match
  48. */
  49. String[] onClass() default {};
  50. }

2.6 Extension Point Sorting

Sorting is also set using the @Activate annotation. Here’s an example of usage; the smaller the order value, the higher the loading priority.

  1. @Activate(order=100)
  2. public class FilterImpl1 implements Filter{}
  3. @Activate(order=200)
  4. public class FilterImpl2 implements Filter{}

3. Dubbo SPI Extension Examples

3.1 Loading Fixed Extension Classes

3.1.1 Writing SPI Interface and Implementation Class

Whether in Java SPI or the SPI implemented in Dubbo, it is necessary to write an interface. However, the interface in Dubbo needs to be annotated with @SPI.

  1. @SPI
  2. public interface DemoSpi {
  3. void say();
  4. }
  5. public class DemoSpiImpl implements DemoSpi {
  6. public void say() {
  7. }
  8. }

3.1.2 Placing Implementation Classes in Specific Directories

From the above code, it can be seen that Dubbo reads extension classes from four directories. We will create a file in the META-INF/dubbo directory with the name of the DemoSpi interface; its content is as follows:

  1. demoSpiImpl = com.xxx.xxx.DemoSpiImpl (the fully qualified name of the DemoSpi interface implementation class)

3.1.3 Usage

  1. public class DubboSPITest {
  2. @Test
  3. public void sayHello() throws Exception {
  4. ExtensionLoader<DemoSpi> extensionLoader =
  5. ExtensionLoader.getExtensionLoader(DemoSpi.class);
  6. DemoSpi demoSpi = extensionLoader.getExtension("demoSpiImpl");
  7. demoSpi.sayHello();
  8. }
  9. }

3.2 Loading Adaptive Extension Classes

Taking Protocol as an example for explanation.

3.2.1 Protocol Interface (Extracting Core Methods)

  1. @SPI("dubbo")
  2. public interface Protocol {
  3. @Adaptive
  4. <T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
  5. @Adaptive
  6. <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
  7. }
  8. public class DubboProtocol extends AbstractProtocol {
  9. ......
  10. @Override
  11. public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
  12. return protocolBindingRefer(type, url);
  13. }
  14. @Override
  15. public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
  16. ......
  17. return exporter;
  18. }
  19. }

3.2.2 Placing Implementation Classes in Specific Directories

In Dubbo, the configuration path is META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol

  1. dubbo=org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol

It should be noted that, in Dubbo, instead of using DubboProtocol directly, the wrapper class is being used.

3.2.3 Usage

  1. public class DubboAdaptiveTest {
  2. @Test
  3. public void sayHello() throws Exception {
  4. URL url = URL.valueOf("dubbo://localhost/test");
  5. Protocol adaptiveProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
  6. adaptiveProtocol.refer(type, url);
  7. }
  8. }

Feedback

Was this page helpful?

Yes No

Last modified September 30, 2024: Update & Translate Overview Docs (#3040) (d37ebceaea7)