第4章:Dubbo扩展点加载机制
1.Java SPI
SPI,Service Provider Interface
Java SPI使用策略模式,一个接口多种实现。我们只申明接口,具体的实现并不在程序中直接指定,而是由程序之外的配置掌控。
具体步骤如下:
(1)定义一个接口及对应的方法
(2)编写一个该接口的实现类
(3)在META-INF/services目录下,创建一个以接口全路径命名的文件,如com.test.spi.PrintService。
(4)文件内容为具体实现类的全路径名,如果有多个,以分行符分隔。
(5)在代码中通过java.util.ServiceLoader来加载具体的实现类。
java SPI目录所示:
java SPI代码:
PrintService.java
package com.test.spi;
public interface PrintService {
void printInfo();
}
PrintServiceImpl.java
package com.test.spi;
public class PrintServiceImpl implements PrintService{
@Override
public void printInfo() {
System.out.println("hello world");
}
}
Application.java
import com.test.spi.PrintService;
import java.util.ServiceLoader;
public class Application {
public static void main(String[] args) {
ServiceLoader<PrintService> serviceServiceLoader = ServiceLoader.load(PrintService.class);
for (PrintService printService : serviceServiceLoader) {
printService.printInfo();
}
}
}
com.test.spi.PrintService文件
com.test.spi.PrintServiceImpl
程序输出:
2.Dubbo SPI
Dubbo SPI对Java SPI进行了改进和优化
- Java SPI会一次性实例化扩展点所有实现,扩展初始化浪费性能,Dubbo SPI只是加载配置文件中的类,并分 类和实例两个层级缓存在内存中
2.1 扩展点的配置规范
配置文件可以放置在META-INF/services/、META-INF/dubbo/、META-INF/dubbo/internal/ 三种目录下的任意一个
文件名是全路径类名
文件内容是key=value格式
2.2 扩展点的特性
2.2.1 自动包装
如果一个类的构造函数包含其他扩展点作为参数,那么这个类就会被认为是Wrapper类
private final Protocol protocol;
public ProtocolFilterWrapper(Protocol protocol) {
if (protocol == null) {
throw new IllegalArgumentException("protocol == null");
}
this.protocol = protocol;
}
2.2.2 自动加载
除了构造函数中带有参数,还可以使用setter方法设置属性值,如果一个扩展类是另外一个扩展点类的成员属性,并且拥有setter方法,那么框架就会自动注入扩展点实例
2.2.3 自适应
使用@Adaptive注解,动态地通过URL中的参数来确定使用哪个具体的实现类
2.2.4 自动激活
某个扩展类的多个实现类同时启用,如Filter扩展点
2.3 扩展点注解
@SPI
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE})
public @interface SPI {
/**
* default extension name
*/
String value() default "";
}
Dubbo框架中都是使用在接口上,标记这个接口是Dubbo SPI接口,即是一个扩展点
传入不同的参数来设置这个接口的默认实现类,如下示例表明Transporter接口使用Netty作为默认实现
@SPI("netty")
public interface Transporter{
}
@Adaptive
扩展点自适应注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE, ElementType.METHOD})
public @interface Adaptive {
String[] value() default {
};
}
在实际应用场景中,一个扩展接口往往会有多种实现类,因为Dubbo是基于URL驱动,所以在运行时,通过传入URL中的某些参数来动态控制具体实现,这便是Dubbo的扩展点自适应特性。
在Dubbo中,@Adaptive一般用来修饰类和接口方法,在整个Dubbo框架中,只有少数几个地方使用在类级别上,如AdaptiveExtensionFactory和AdaptiveCompiler,其余都标注在方法上。
标记在方法上时,会自动生成和编译一个动态的Adaptive类
如果在放在实现类上,则整个实现类会直接作为默认实现,使用到了类和实例缓存避免重复实例化的开销
@Active
扩展点自动激活注解
主要作用是有多个扩展点实现需要根据不同条件实例化