Dubbo原理解析-Dubbo内核实现之SPI简单介绍

Dubbo采用 微内核 + 插件体系,使得设计优雅,扩展性强。那所谓的微内核+插件体系是如何实现的呢!大家是否熟悉spi(service providerinterface)机制,

即我们定义了服务接口标准,让厂商去实现(如果不了解spi的请谷歌百度下),

jdk通过ServiceLoader类实现spi机制的服务查找功能。


JDK实现spi服务查找: ServiceLoader

首先定义下示例接口

复制代码
public interface Spi {

       booleanisSupport(String name);
       String sayHello();

}
复制代码

  ServiceLoader会遍历所有jar查找META-INF/services/com.example.Spi文件

A厂商提供实现

复制代码
package com.b.example;
  public class SpiBImpl implements Spi {
  public boolean isSupport(String name) {
    return"SPIB".equalsIgnoreCase(name.trim()); 
  }
  public String syaHello() {
       return “hello 我是厂商B”;
  }
}
复制代码

在A厂商提供的jar包中的META-INF/services/com.example.Spi文件内容为:

com.a.example.SpiAImpl        #厂商A的spi实现全路径类名

  B厂商提供实现

复制代码
package com.b.example;
  public class SpiBImpl implements Spi {
   public boolean isSupport(String name) {
     return"SPIB".equalsIgnoreCase(name.trim()); 
  }
  public String syaHello() {
       return “hello 我是厂商B”;
  }
}
复制代码

在B厂商提供的jar包中的META-INF/services/com.example.Spi文件内容为:

com.b.example.SpiBImpl        #厂商B的spi实现全路径类名

ServiceLoader.load(Spi.class)读取厂商A、B提供jar包中的文件,ServiceLoader实现了Iterable接口,

可通过while for循环语句遍历出所有实现。

一个接口多种实现,就如策略模式一样提供了策略的实现,但是没有提供策略的选择, 使用方可使用 isSupport 方法,

根据业务传入厂商名来选择具体的厂商。

复制代码
public class SpiFactory {
       //读取配置获取所有实现
       privatestatic ServiceLoader spiLoader = ServiceLoader.load(Spi.class);
       //根据名字选取对应实现
       public static Spi getSpi(String name) {
              for(Spi spi : spiLoader) {
                     if(spi.isSupport(name) ) {
                            return spi;
                     }
              }
              return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值