消费者模块
从配置到代理
- 解析配置:ReferenceConfig, DubboBootstrap,读取配置并合并
- 注册中心订阅:RegistryDirectory,向 Nacos/ZooKeeper 订阅服务列表
- 目录路由:RouterChain,根据规则对 Provider 列表过滤
- 集群封装:Cluster, ClusterInvoker,实现容错机制
- 负载均衡:LoadBalance,支持 Random/RoundRobin/ConsistentHash/LeastActive
- 动态代理:ProxyFactory,生成本地代理类
- 连接池 & 网络:ExchangeClient(Netty),支持 Triple/Dubbo 协议
运行时调用链
业务代码 → 接口代理 → Filter 链 → ClusterInvoker
↓ ↓
Async/Future LoadBalance
↓ ↓
ExchangeClient → Netty → Provider
关键扩展点(SPI)
- Filter:ExceptionFilter, TraceFilter, SentinelFilter
- Cluster:Failover, Failfast, Broadcast, Forking
- LoadBalance:Random, RoundRobin, LeastActive, ConsistentHash
POM 依赖
<dependencies>
<dependency>
<groupId>icu.wzk</groupId>
<artifactId>wzk-service-api</artifactId>
</dependency>
</dependencies>
消费者定义
@Component
public class ConsumerComponent {
@Reference
private WzkHelloService wzkHelloService;
public String sayHello(String name) {
return wzkHelloService.sayHello(name);
}
}
配置文件
dubbo.application.name=service-consumer
dubbo.registry.address=zookeeper://10.10.52.38:2181
启动类
生产者启动
public class DubboPureMain {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ProviderConfiguration.class);
context.start();
System.in.read();
}
}
消费者启动
public class AnnotationConsumerMain {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
context.start();
ConsumerComponent service = context.getBean(ConsumerComponent.class);
while (true) {
try {
String hello = service.sayHello("world!");
System.out.println("result: " + hello);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
高频配置参数
| 参数 | 说明 |
|---|
| timeout | RPC 调用超时时间 (ms) |
| retries | 失败重试次数 |
| check | 启动时是否校验 Provider 存在 |
| lazy | 首次调用时才创建连接 |
| cache | 开启本地方法缓存 |
| mock | 服务降级策略 |
| async | 是否异步调用 |