美文网首页
dubbo进阶

dubbo进阶

作者: 策马踏清风 | 来源:发表于2021-04-05 23:19 被阅读0次

RPC 服务暴露与引入

服务方

  1. 中转对象,用于中转代理对象的网络请求,参数、返回结果(Protocol.export创建)。

消费方

  1. 动态代理,为接口创建动态代理类,做请求发送功能。
  2. 使用Protocol.referInvoker,用于发送网络请求

Spring Rmi

服务提供者

// Spring rmi 中转对象
@Bean
public RmiServiceExporter serviceExporter() {
    RmiServiceExporter res = new RmiServiceExporter();
    // 代理接口的路径名称
    res.setServiceName(TestService.class.getName());
    // 端口
    res.setRegistryPort(port);
    // 暴露给外部访问的接口
    res.setServiceInterface(TestService.class);
    // 实际使用对象
    res.setService(new TestServiceImpl())
}

SPI机制

本质是策略模式,一个接口,多个实现。根据不同策略选择,进行不同的策略。

  1. java spi例子
public static void main(String[] args) throws Exception {
    // 使用spi加载接口的具体实现类
    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获取

com.test.service.impl.testServiceImpl1
com.test.service.impl.testServiceImpl2
com.test.service.impl.testServiceImpl3
  1. dubbo spi
    • @SPI注释标记的接口都可以使用dubbo spi进行拓展
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <version>2.5.7</version>
    <!-- 设置成编译期间使用,否则放入dubbo项目后会jar冲突 -->
    <scope>provided</scope>
</dependency>
  • LoadBalance负载均衡
public class MyLoadBalance implements LoadBalance {
    // 自定义负载均衡策略
    // invokers 是所有provider的实现,此方法主要是通过自定义策略选择返回一个provider的实现
    @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稍微不同,需要指定一个名称
myLoad=com.test.service.impl.MyLoadBalance
  • 使用此负载均衡
<dubbo:reference id="TestService" interface="com.test.service.TestService" loadbalance="myLoad"/>
  1. spi原理
    • 为所有接口生产一个加载器
    • 使用加载器生成接口代理对象
    • 使用代理对象执行方法时,根据参数判断使用那个实现类

相关文章

网友评论

      本文标题:dubbo进阶

      本文链接:https://www.haomeiwen.com/subject/skbjkltx.html