dubbo引用
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
和导出一样,引用标签,最后会解析成ReferenceBean。
看实现接口
FactoryBean:所以是工厂方法,最终注入spring的对象是调用FactoryBean的getObject方法获得的对象。
ApplicationContextAware:注入ApplicationContext对象。
InitializingBean:初始化了spring之后调用afterPropertiesSet方法。
DisposableBean:spring容器销毁会调用destory方法。这里什么没做。
public class ReferenceBean extends ReferenceConfig implements FactoryBean, ApplicationContextAware, InitializingBean, DisposableBean {
@Override
@SuppressWarnings({"unchecked"})
public void afterPropertiesSet() throws Exception {
if (applicationContext != null) {
// 从applicationContext中获取ConfigCenterBean类型的实例列表。这里什么也没做
BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ConfigCenterBean.class, false, false);
}
...省略代码。从spring容器获取各种配置类set保存到成员方法中
// 是否初始化。dubbo:reference可以配置init属性。
if (shouldInit()) {
// 真正获取对象
getObject();
}
}
@Override
public Object getObject() {
return get();
}
public synchronized T get() {
// 检查和更新一下配置属性,导出服务也有这个方法,不看
checkAndUpdateSubConfigs();
if (destroyed) {
throw new IllegalStateException("The invoker of ReferenceConfig(" + url + ") has already destroyed!");
}
if (ref == null) {
init();
}
return ref;
}
private void init() {
...省略代码。各种拼装配置参数到map
ref = createProxy(map);
String serviceKey = URL.buildKey(interfaceName, group, version);
ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes));
initialized = true;
}
private T createProxy(Map map) {
// 是否jvm内部就可以引用。根据url判定。false
if (shouldJvmRefer(map)) {
URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map);
invoker = REF_PROTOCOL.refer(interfaceClass, url);
if (logger.isInfoEnabled()) {
logger.info("Using injvm service " + interfaceClass.getName());
}
} else {
urls.clear(); // reference retry init will add url to urls, lead to OOM
// url不为空,则说明是dubbo:reference直接指定了url调用
if (url != null && url.length() > 0) { // user specified URL, could be peer-to-peer address, or register center's address.
String[] us = SEMICOLON_SPLIT_PATTERN.split(url);
if (us != null && us.length > 0) {
for (String u : us) {
URL url = URL.valueOf(u);
if (StringUtils.isEmpty(url.getPath())) {
url = url.setPath(interfaceName);
}
// 是否是注册中心
if (REGISTRY_PROTOCOL.equals(url.getProtocol())) {
urls.add(url.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
} else {
urls.add(ClusterUtils.mergeUrl(url, map));
}
}
}
} else { // assemble URL from register center's configuration
// if protocols not injvm checkRegistry
// 不是本地协议引用,通过注册中心获取url,常用方式
if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){
checkRegistry();
// 加载注册中心url
List us = loadRegistries(false);
// 只有一个注册中心。us = registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?...
if (CollectionUtils.isNotEmpty(us)) {
for (URL u : us) {
URL monitorUrl = loadMonitor(u);
if (monitorUrl != null) {
map.put(MONITOR_KEY, URL.encode(monitorUrl.toFullString()));
}
urls.add(u.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
}
}
if (urls.isEmpty()) {
throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config to your spring config.");
}
}
}
// urls添加的注册中心url:registry://。。。这里只有一个。
if (urls.size() == 1) {
// REF_PROTOCOL自然是protocol扩展适配器类,因为url是registry协议,所以自然调用的是RegistryProtocol的refer方法
invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0));
} else {
// 如果urls是多个注册中心,则便利各个url生成多个invoker,然后用cluster把多个invoker合并成一个invoker
。。。暂时不看
}
// create service proxy
return (T) PROXY_FACTORY.getProxy(invoker);
}
public Invoker refer(Class type, URL url) throws RpcException {
// 组成成zookeeper://..
url = URLBuilder.from(url)
.setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
.removeParameter(REGISTRY_KEY)
.build();
Registry registry = registryFactory.getRegistry(url);
// type是引用的接口
if (RegistryService.class.equals(type)) {
return proxyFactory.getInvoker((T) registry, type, url);
}
// 如有有group分组,就从url参数中获取匹配。这里没有
// group="a,b" or group="*"
Map qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
String group = qs.get(GROUP_KEY);
if (group != null && group.length() > 0) {
if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
return doRefer(getMergeableCluster(), registry, type, url);
}
}
return doRefer(cluster, registry, type, url);
}
private Invoker doRefer(Cluster cluster, Registry registry, Class type, URL url) {
// RegistryDirectory是比较重要的类,有订阅方法,订阅从注册中心获取远程服务地址就是这个类
RegistryDirectory directory = new RegistryDirectory(type, url);
directory.setRegistry(registry);
directory.setProtocol(protocol);
// all attributes of REFER_KEY
Map parameters = new HashMap(directory.getUrl().getParameters());
// 构建订阅url。consumer://。。。
URL subscribeUrl = new URL(CONSUMER_PROTOCOL, parameters.remove(REGISTER_IP_KEY), 0, type.getName(), parameters);
// 不是通用接口(interface=*),切需要注册。这里符合
if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true)) {
directory.setRegisteredConsumerUrl(getRegisteredConsumerUrl(subscribeUrl, url));
// 往Zookeeper中注册consumer://,就是创建consumer节点。
registry.register(directory.getRegisteredConsumerUrl());
}
directory.buildRouterChain(subscribeUrl);
// 订阅consumer://。可以看到category有三个:providers、configurators、routes。后面会针对这三个节点添加订阅
directory.subscribe(subscribeUrl.addParameter(CATEGORY_KEY,
PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY));
Invoker invoker = cluster.join(directory);
ProviderConsumerRegTable.registerConsumer(invoker, url, subscribeUrl, directory);
return invoker;
}
public void subscribe(URL url) {
setConsumerUrl(url);
CONSUMER_CONFIGURATION_LISTENER.addNotifyListener(this);
serviceConfigurationListener = new ReferenceConfigurationListener(this, url);
// registry是zookeeperRegistry。这里真真添加订阅
registry.subscribe(url, this);
}
ZookeeperRegistry继承于FailbackRegistry。跟服务导出,快速失败的逻辑是一样的。
@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
try {
// 是否是通用接口。不看
if (ANY_VALUE.equals(url.getServiceInterface())) {
...省略
} else {
List urls = new ArrayList<>();
// 前面看到category有三个。providers、configurators、routes。所以这里path有三个:/dubbo/**接口名/providers,/dubbo/**接口名/configurators、/dubbo/**接口名/routes。
for (String path : toCategoriesPath(url)) {
ConcurrentMap listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
// 监听器是内部类,最终监听调用的是ZookeeperRegistry.this.notify方法
listeners.putIfAbsent(listener, (parentPath, currentChilds) -> ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)));
zkListener = listeners.get(listener);
}
// zkClient内部逻辑会判定,如果没有这个节点就创建这个节点。
zkClient.create(path, false);
// zkClient跟服务导出一样是:CuratorZookeeperClient。
// 添加监听器,并且返回节点下的子节点。如果子节点为空,则通过consumer协议构建empty://协议返回。
// 所以providers节点下自然是服务地址方地址(可以登录zookeeper查看)
// configurators和routes没有子节点。所以返回empty://。
List children = zkClient.addChildListener(path, zkListener);
if (children != null) {
urls.addAll(toUrlsWithEmpty(url, path, children));
}
}
// 添加完之后,手动调用唤醒方法。前面添加了三个节点的监听器。并返回了三个节点下的子节点。
// 一个是dubbo://...真正的服务地址地址。另外两个是empty://地址
notify(url, listener, urls);
}
} catch (Throwable e) {
throw new RpcException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
protected void notify(URL url, NotifyListener listener, List urls) {
// keep every provider's category.
Map> result = new HashMap<>();
for (URL u : urls) {
if (UrlUtils.isMatch(url, u)) {
// 获取url的category参数,有:providers、configurators、routes。
String category = u.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
// 以category分组,保存在result
List categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
categoryList.add(u);
}
}
if (result.size() == 0) {
return;
}
Map> categoryNotified = notified.computeIfAbsent(url, u -> new ConcurrentHashMap<>());
for (Map.Entry> entry : result.entrySet()) {
String category = entry.getKey();
List categoryList = entry.getValue();
categoryNotified.put(category, categoryList);
// listener是之前传入的RegistryDirectory。categoryList是result遍历:有dubbo://...,empty://,empty://
listener.notify(categoryList);
// We will update our cache file after each notification.
// When our Registry has a subscribe failure due to network jitter, we can return at least the existing cache URL.
saveProperties(url);
}
}
@Override
public synchronized void notify(List urls) {
// 过滤,并按vonfigurator、route、provider分三组。
Map> categoryUrls = urls.stream()
.filter(Objects::nonNull)
.filter(this::isValidCategory)
.filter(this::isNotCompatibleFor26x)
.collect(Collectors.groupingBy(url -> {
if (UrlUtils.isConfigurator(url)) {
return CONFIGURATORS_CATEGORY;
} else if (UrlUtils.isRoute(url)) {
return ROUTERS_CATEGORY;
} else if (UrlUtils.isProvider(url)) {
return PROVIDERS_CATEGORY;
}
return "";
}));
// 如果是configurator协议则toConfigurators处理,否则不处理。toConfigurators方法内部会忽略empty://。
List configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
// 如果是route协议则toRoute处理,否则不处理。toRoute方法内部会忽略empty://。
List routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
toRouters(routerURLs).ifPresent(this::addRouters);
// providers协议则refreshOverrideAndInvoker处理。
List providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
refreshOverrideAndInvoker(providerURLs);
}
private void refreshInvoker(List invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null");
// 如果providers节点下已经空了,则说明服务提供没了,则这里invokerUrls则是empty://,这里就会调用destroyAllInvokers方法销毁所有invoke。
if (invokerUrls.size() == 1
&& invokerUrls.get(0) != null
&& EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
this.forbidden = true; // Forbid to access
this.invokers = Collections.emptyList();
routerChain.setInvokers(this.invokers);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow to access
Map> oldUrlInvokerMap = this.urlInvokerMap; // local reference
if (invokerUrls == Collections.emptyList()) {
invokerUrls = new ArrayList<>();
}
if (invokerUrls.isEmpty() && this.cachedInvokerUrls != null) {
invokerUrls.addAll(this.cachedInvokerUrls);
} else {
this.cachedInvokerUrls = new HashSet<>();
this.cachedInvokerUrls.addAll(invokerUrls);//Cached invoker urls, convenient for comparison
}
if (invokerUrls.isEmpty()) {
return;
}
// 真正通过provider://,构建invoke类。key手机provider url。v
Map> newUrlInvokerMap = toInvokers(invokerUrls);// Translate url list to Invoker map
。。。省略代码
try {
// 新旧invokder对比,销毁不可用的旧的invoker。
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn("destroyUnusedInvokers error. ", e);
}
}
}
private Map> toInvokers(List urls) {
。。。省略代码
// url是dubbo://,所以这里自然调用的是DubboProtocol.refer方法
invoker = new InvokerDelegate<>(protocol.refer(serviceType, url), url, providerUrl);
return newUrlInvokerMap;
}
@Override
public Invoker refer(Class type, URL url) throws RpcException {
return new AsyncToSyncInvoker<>(protocolBindingRefer(type, url));
}
@Override
public Invoker protocolBindingRefer(Class serviceType, URL url) throws RpcException {
// 如果url有optimize参数,就会调用对应的接口方法,注册。这里没有不管
optimizeSerialization(url);
// create rpc invoker.
//真正构建invoker。getClient猜都能猜到是建立远程服务提供者的服务连接
DubboInvoker invoker = new DubboInvoker(serviceType, url, getClients(url), invokers);
invokers.add(invoker);
return invoker;
}
private ExchangeClient[] getClients(URL url) {
// 是否使用共享连接。不同的远程接口,相同的远程应用应该会使用同一个连接
boolean useShareConnect = false;
int connections = url.getParameter(CONNECTIONS_KEY, 0);
List shareClients = null;
// 下文的英文注释,也可以看出来,如果没有手动配置连接,则是共享连接,一个服务只有一个连接
// if not configured, connection is shared, otherwise, one connection for one service
if (connections == 0) {
useShareConnect = true;
/**
* The xml configuration should have a higher priority than properties.
*/
String shareConnectionsStr = url.getParameter(SHARE_CONNECTIONS_KEY, (String) null);
connections = Integer.parseInt(StringUtils.isBlank(shareConnectionsStr) ? ConfigUtils.getProperty(SHARE_CONNECTIONS_KEY,
DEFAULT_SHARE_CONNECTIONS) : shareConnectionsStr);
//
shareClients = getSharedClient(url, connections);
}
ExchangeClient[] clients = new ExchangeClient[connections];
for (int i = 0; i < clients.length; i++) {
if (useShareConnect) {
clients[i] = shareClients.get(i);
} else {
clients[i] = initClient(url);
}
}
return clients;
}
private List getSharedClient(URL url, int connectNum) {
// 获得ip和端口:192.168.106.1:20880
String key = url.getAddress();
List clients = referenceClientMap.get(key);
if (checkClientCanUse(clients)) {
batchClientRefIncr(clients);
return clients;
}
// 这个锁的方式可以借鉴一下。我之前一直synchronized("".internal())。
locks.putIfAbsent(key, new Object());
synchronized (locks.get(key)) {
clients = referenceClientMap.get(key);
// dubbo check
if (checkClientCanUse(clients)) {
batchClientRefIncr(clients);
return clients;
}
connectNum = Math.max(connectNum, 1);
if (CollectionUtils.isEmpty(clients)) {
// 这里建立连接
clients = buildReferenceCountExchangeClientList(url, connectNum);
referenceClientMap.put(key, clients);
}
。。。省略代码
return clients;
}
}
private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) {
ExchangeClient exchangeClient = initClient(url);
return new ReferenceCountExchangeClient(exchangeClient);
}
private ExchangeClient initClient(URL url) {
// 获取连接类型,默认是netty
String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT));
// 添加编码方式
url = url.addParameter(CODEC_KEY, DubboCodec.NAME);
//设置心跳时间
url = url.addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT));
// BIO is not allowed since it has severe performance issue.
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
throw new RpcException("Unsupported client type: " + str + "," +
" supported client type is " + StringUtils.join(ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(), " "));
}
ExchangeClient client;
try {
// connection should be lazy
if (url.getParameter(LAZY_CONNECT_KEY, false)) {
client = new LazyConnectExchangeClient(url, requestHandler);
} else {
// 没有显示制定lasy连接,就进入这里。requestHandler是DubboProtol的内部类,之后处理消息就是这个类
// 接下来的逻辑和服务导出差不多,不看了
client = Exchangers.connect(url, requestHandler);
}
} catch (RemotingException e) {
throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e);
}
return client;
}
至此,从注册中心获取服务地址,构造invoker看完了。
// // 订阅完之后,directory内部就维护了以远程服务有连接的invoker
directory.subscribe(subscribeUrl.addParameter(CATEGORY_KEY,
PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY));
//cluster是spi set注入的。spi注入的肯定是可适配扩展类。因为directory的url参数中没有指明cluster,所以默认的是FailoverCluster。外面还有一层MockClusterWrapper,这个不管。所以这个invoker可以看成是一个FailoverClusterInvoker。
Invoker invoker = cluster.join(directory);
接着看怎么进行服务调用的。注入到spring中的引用对象到底是怎样的
回到createProxy方法。
// ProxyFactory默认是javassist。
return (T) PROXY_FACTORY.getProxy(invoker);
public T getProxy(Invoker invoker, Class>[] interfaces) {
// Proxy.getProxy(interfaces)会用javassist动态构建一个代理。看newInstance传参就知道,这个代理的构造方法接受一个InvokerInvocationHandler
// 代理类的逻辑就是。代理类invoke,会调用构造方法传参过来的InvokerInvocationHandler的invoke方法
return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
}
至此,可以看到,最后返回给spring容器的是一个代理类。这个代理类调用的时候,其实最终调用的就是InvokerInvocationHandler的invoke方法。
所以看一下InvokerInvocationHandler的invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
Class>[] parameterTypes = method.getParameterTypes();
if (method.getDeclaringClass() == Object.class) {
return method.invoke(invoker, args);
}
if ("toString".equals(methodName) && parameterTypes.length == 0) {
return invoker.toString();
}
if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
return invoker.hashCode();
}
if ("equals".equals(methodName) && parameterTypes.length == 1) {
return invoker.equals(args[0]);
}
// 最终调用的是构造方法里传过来的invoker的invoke方法。之前传过来的是MockClusterWrapper包装的FailoverClusterInvoker
// 这里把method和args封装在RpcInvocation进行传输
return invoker.invoke(new RpcInvocation(method, args)).recreate();
}
看FailoverClusterInvoker的invoke方法
@Override
public Result invoke(final Invocation invocation) throws RpcException {
checkWhetherDestroyed();
// binding attachments into invocation.
Map contextAttachments = RpcContext.getContext().getAttachments();
if (contextAttachments != null && contextAttachments.size() != 0) {
((RpcInvocation) invocation).addAttachments(contextAttachments);
}
// 之前cluster维护了构造好的RegistryDirectly。而RegistryDirectly维护了已经和远程服务建立好链接的invoker。所以这里不用看逻辑都知道,是把那些invoker取出来。为什么是数组,因为可以存在多个连接调用。
List> invokers = list(invocation);
// 获取负载均衡策略
LoadBalance loadbalance = initLoadBalance(invokers, invocation);
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
// 调用
return doInvoke(invocation, invokers, loadbalance);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(Invocation invocation, final List> invokers, LoadBalance loadbalance) throws RpcException {
List> copyInvokers = invokers;
checkInvokers(copyInvokers, invocation);
String methodName = RpcUtils.getMethodName(invocation);
// 获取重试次数
int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
if (len <= 0) {
len = 1;
}
// retry loop.
RpcException le = null; // last exception.
List> invoked = new ArrayList>(copyInvokers.size()); // invoked invokers.
Set providers = new HashSet(len);
// for循环重试
for (int i = 0; i < len; i++) {
//Reselect before retry to avoid a change of candidate `invokers`.
//NOTE: if `invokers` changed, then `invoked` also lose accuracy.
if (i > 0) {
checkWhetherDestroyed();
copyInvokers = list(invocation);
// check again
checkInvokers(copyInvokers, invocation);
}
...省略代码
Invoker invoker = select(loadbalance, invocation, copyInvokers, invoked);
invoked.add(invoker);
RpcContext.getContext().setInvokers((List) invoked);
try {
// 真正调用。这个invoker就是之前订阅zookeeper构建的RegistryDirectly的包装过的DubboInvoker
Result result = invoker.invoke(invocation);
return result;
} catch (RpcException e) {
if (e.isBiz()) { // biz exception.
throw e;
}
le = e;
} catch (Throwable e) {
le = new RpcException(e.getMessage(), e);
} finally {
providers.add(invoker.getUrl().getAddress());
}
}
throw new RpcException(le.getCode(), "Failed to invoke the method "
+ methodName + " in the service " + getInterface().getName()
+ ". Tried " + len + " times of the providers " + providers
+ " (" + providers.size() + "/" + copyInvokers.size()
+ ") from the registry " + directory.getUrl().getAddress()
+ " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
+ Version.getVersion() + ". Last error is: "
+ le.getMessage(), le.getCause() != null ? le.getCause() : le);
}
dubboInvoker外面包装的Wrapper等不看
@Override
protected Result doInvoke(final Invocation invocation) throws Throwable {
RpcInvocation inv = (RpcInvocation) invocation;
final String methodName = RpcUtils.getMethodName(invocation);
inv.setAttachment(PATH_KEY, getUrl().getPath());
inv.setAttachment(VERSION_KEY, version);
// dubboInvoker内部已经维护了跟远程服务建立了连接的client
ExchangeClient currentClient;
if (clients.length == 1) {
currentClient = clients[0];
} else {
currentClient = clients[index.getAndIncrement() % clients.length];
}
try {
// 方法是否有返回值
boolean isOneway = RpcUtils.isOneway(getUrl(), invocation);
int timeout = getUrl().getMethodParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT);
// 没有返回值
if (isOneway) {
boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false);
// 发送接口调用
currentClient.send(inv, isSent);
RpcContext.getContext().setFuture(null);
return AsyncRpcResult.newDefaultAsyncResult(invocation);
} else {
AsyncRpcResult asyncRpcResult = new AsyncRpcResult(inv);
// 发送接口调用
CompletableFuture
关于序列化和反序列化,就是netty的handler处理的(反序列化DecodeHandler),通过spi动态扩展选择哪种序列化方式。具体源码就不看了。