了解dubbo的adaptive自适应扩展点(3)

175 阅读1分钟

dubbo的Adaptive机制

为什么需要Adaptive机制

简单来说,dubbo希望在调用过程中动态指定实现类。

区分固定扩展点和自适应扩展点

固定扩展点

public class DubboSPITest {

    @Test
    public void sayHello() throws Exception {
        ExtensionLoader<DemoSpi> extensionLoader = 
            ExtensionLoader.getExtensionLoader(DemoSpi.class);
        DemoSpi dmeoSpi = extensionLoader.getExtension("demoSpiImpl");
        optimusPrime.sayHello();
    }
}

自适应扩展点

这个以 Protocol 为例进行说明

Protocol 接口(抽取部分核心方法)
@SPI("dubbo")
public interface Protocol {
    @Adaptive
    <T> Exporter<T> export(Invoker<T> invoker) throws RpcException;

    @Adaptive
    <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
}

public class DubboProtocol extends AbstractProtocol {
    ......
    @Override
    public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
        return protocolBindingRefer(type, url);
    }
    
    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        ......
        return exporter;
    }
}
将实现类放在特定目录下

在 dubbo 中,该配置路径 META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol。需要说明一点的是,在 dubbo 中,并不是直接使用 DubboProtocol 的,而是使用的是其包装类。

dubbo=org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol
使用,根据url参数的dubbo,指定在调用的过程中使用dubbo协议
public class DubboAdaptiveTest {

    @Test
    public void sayHello() throws Exception {
        URL url = URL.valueOf("dubbo://localhost/test");
        Protocol adaptiveProtocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
        adaptiveProtocol.refer(type, url);
    }
}