文章字数:398,阅读全文大约需要1分钟
SPI机制
本质是策略模式,一个接口,多个实现。根据不同策略选择,进行不同的策略。
java spi
例子
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) throws Exception { ServiceLoader<TestService> spiLoader = ServiceLoader.load(TestService.class); Iterator<SpiService> iteratorSpi = spiLoader.iterator(); while(iteratorSpi.hasNext()) { TestService testService = spiLoader,next(); } }
|
META-INF.services
文件夹内创建com.test.service.testService
文件,即接口名称命名的文件
其中指定了此接口指定的实现类,可用spi
获取
1 2 3
| com.test.service.impl.testServiceImpl1 com.test.service.impl.testServiceImpl2 com.test.service.impl.testServiceImpl3
|
dubbo spi
@SPI
注释标记的接口都可以使用dubbo spi
进行拓展
1 2 3 4 5 6 7
| <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.5.7</version> <scope>provided</scope> </dependency>
|
1 2 3 4 5 6 7 8 9
| public class MyLoadBalance implements LoadBalance { @Override public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { return invokers.get(0); } }
|
- ``META-INF.dubbo
中创建接口全名的文件
com.alibaba.dubbo.rpc.cluster.LoadBalance`
- 和
java
自带的spi
稍微不同,需要指定一个名称
1
| myLoad=com.test.service.impl.MyLoadBalance
|
1
| <dubbo:reference id="TestService" interface="com.test.service.TestService" loadbalance="myLoad"/>
|
spi
原理
- 为所有接口生产一个加载器
- 使用加载器生成接口代理对象
- 使用代理对象执行方法时,根据参数判断使用那个实现类