首先来看一段export服务的demo代码:
ServiceConfig<MotanDemoService> motanDemoService = new ServiceConfig<>();
// 设置接口及实现类
motanDemoService.setInterface(MotanDemoService.class);
motanDemoService.setRef(new MotanDemoServiceImpl());
// 配置服务的group以及版本号
motanDemoService.setGroup("motan-demo-rpc");
motanDemoService.setVersion("1.0");
// 配置注册中心直连调用
// RegistryConfig directRegistry = new RegistryConfig();
// directRegistry.setRegProtocol("local");
// directRegistry.setCheck("false"); //不检查是否注册成功
// motanDemoService.setRegistry(directRegistry);
// 配置ZooKeeper注册中心
RegistryConfig zookeeperRegistry = new RegistryConfig();
zookeeperRegistry.setRegProtocol("zookeeper");
zookeeperRegistry.setAddress("127.0.0.1:2181");
motanDemoService.setRegistry(zookeeperRegistry);
// 配置RPC协议
ProtocolConfig protocol = new ProtocolConfig();
protocol.setId("motan");
protocol.setName("motan");
motanDemoService.setProtocol(protocol);
motanDemoService.setApplication("motan");
motanDemoService.setExport("motan:8002");
motanDemoService.export();
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
System.out.println("server start...");
服务配置的组装过程中设置了注册配置和协议配置,整体的类图如下:
这里最关键的方法就是export方法了,所有需要的配置信息已经组装完毕,开始暴露服务了。
public synchronized void export() {
//检查状态,避免重复export
if (exported.get()) {
LoggerUtil.warn(String.format("%s has already been expoted, so ignore the export request!", interfaceClass.getName()));
return;
}
//检查接口和方法
checkInterfaceAndMethods(interfaceClass, methods);
//解析出注册地址 zookeeper://127.0.0.1:2181/com.weibo.api.motan.registry.RegistryService?group=default_rpc
List<URL> registryUrls = loadRegistryUrls();
if (registryUrls == null || registryUrls.size() == 0) {
throw new IllegalStateException("Should set registry config for service:" + interfaceClass.getName());
}
Map<String, Integer> protocolPorts = getProtocolAndPort();
for (ProtocolConfig protocolConfig : protocols) {
Integer port = protocolPorts.get(protocolConfig.getId());
if (port == null) {
throw new MotanServiceException(String.format("Unknow port in service:%s, protocol:%s", interfaceClass.getName(),
protocolConfig.getId()));
}
//真正的export
doExport(protocolConfig, port, registryUrls);
}
afterExport();
}