- 泛化调用
泛化接口调用方式主要用于客户端没有 API 接口及模型类元的情况,参数及返回值中的所有 POJO 均用 Map 表示,通常用于框架集成,比如:实现一个通用的服务测试框架,可通过 GenericService 调用所有服务实现。(摘自:https://dubbo.apache.org/zh/docs/advanced/generic-reference/)
基础用法:
// 连接注册中心配置
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zk.xxx.com:2181");
registry.setProtocol("zookeeper");
registry.setGroup("xxx/xxx/xxx");
ApplicationConfig applicationConfig = new ApplicationConfig("appCode");
// 引用远程服务
// 该实例很重量,里面封装了所有与注册中心及服务提供方连接,请缓存
ReferenceConfig reference = new ReferenceConfig();
// 弱类型接口名
reference.setInterface("xxx.xxx.xxxService");
reference.setVersion("1.0.0");
// 声明为泛化接口
reference.setGeneric(true);
reference.setApplication(applicationConfig);
reference.setRegistry(registry);
reference.setRetries(1);
reference.setTimeout(5000);
// 用org.apache.dubbo.rpc.service.GenericService可以替代所有接口引用
GenericService genericService = reference.get();
// 基本类型以及Date,List,Map等不需要转换,直接调用
Object result = genericService.$invoke("getUser", new String[] {"java.lang.String"},
new Object[] {"zhangsan"});
System.out.println(result);
原理分析:
- dubbo服务发现流程:https://dubbo.apache.org/zh/docs/concepts/service-discovery/
我们重点看下第四步,消费端想提供者发起的是invoke调用,那什么是invoke调用呢?什么又是invoker? - invoker
mInvoker是Dubbo的核心模型,是Dubbo中的实体域,也就是真实存在的。其他模型都向它靠拢或转换成它,它也就代表一个可执行体,可向它发起invoke调用。在服务提供方,Invoker用于调用服务提供类。在服务消费方,Invoker用于执行远程调用。
生产者暴露服务流程总体分为两步,第一步是接口实现类转换为Invoker,第二步是Invoker转换为Exporter并放入ExporterMap,暴露服务流程图如下:
生产者通过ProxyFactory.getInvoker创建Invoker(AbstractProxyInvoker):
public class JdkProxyFactory extends AbstractProxyFactory {
@Override
public Invoker getInvoker(T proxy, Class type, URL url) {
return new AbstractProxyInvoker(proxy, type, url) {
@Override
protected Object doInvoke(T proxy, String methodName,
Class>[] parameterTypes,
Object[] arguments) throws Throwable {
// proxy为被代理对象 -> xxx.xxx.xxxService
Method method = proxy.getClass().getMethod(methodName, parameterTypes);
return method.invoke(proxy, arguments);
}
};
}
}
消费者引用服务流程图:
首先spring解析reference标签,然后加载为ReferenceBean,存储在ReferenceConfig中,然后调用refer接口;如果是本地引用会走InJvmProtocol方法,如果是远程引用会走RegistryProtocol(负责与注册中心交互)-ZookeeperRegistry-DubboProtocol(负责与服务提供者建立连接)-DubboInvoker;最终显示创建Invoker,通过getProxy创建代理,由InvokerInvocationHandler处理请求。
new InjvmInvoker(serviceType, url, url.getServiceKey(), exporterMap) //本地暴露 new DubboInvoker (serviceType, url, getClients(url), invokers) //远程暴露
创建完成后再通过ProxyFactory.getProxy创建代理:
public class JdkProxyFactory extends AbstractProxyFactory {
@Override
public T getProxy(Invoker invoker, Class>[] interfaces) {
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
}
}
思考:为什么生产者和消费者都要转换为Invoker,而不是直接调用呢?
3. 过滤器链路
dubbo的真实调用都转换为Invoker,这样就可以通过责任链模式增强Invoker功能。
public class ProtocolFilterWrapper implements Protocol {
private final Protocol protocol;
@Override
public Exporter export(Invoker invoker) throws RpcException {
if (UrlUtils.isRegistry(invoker.getUrl())) {
return protocol.export(invoker);
}
//生产者增加过滤器链
return protocol.export(buildInvokerChain(invoker, SERVICE_FILTER_KEY, CommonConstants.PROVIDER));
}
@Override
public Invoker refer(Class type, URL url) throws RpcException {
if (UrlUtils.isRegistry(url)) {
return protocol.refer(type, url);
}
//消费者增加过滤器链
return buildInvokerChain(protocol.refer(type, url), REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
}
无论是生产者还是消费者都会创建过滤器链,我们看看buildInvokerChain这个方法:
private staticInvoker buildInvokerChain(final Invoker invoker, String key, String group) { Invoker last = invoker; // 1.加载所有包含@Activate注解的过滤器 // 2.根据group过滤得到过滤器列表 (provider/consumer) // 3.Invoker最终被放到过滤器链尾部 //具体实现可以看: org.apache.dubbo.common.extension.AbstractFoundationExtensionLoader#getActivateExtension List filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group); if (!filters.isEmpty()) { for (int i = filters.size() - 1; i >= 0; i--) { final Filter filter = filters.get(i); final Invoker next = last; //构造一个简化Invoker last = new Invoker () { ... @Override public Result invoke(Invocation invocation) throws RpcException { Result asyncResult; try { // 构造过滤器链路 asyncResult = filter.invoke(next, invocation); } catch (Exception e) { .... throw e; } return asyncResult.whenCompleteWithContext((r, t) -> { ... }); } .... }; } } return last; }
生产者最终生成链路:
EchoFilter -> ClassloaderFilter -> GenericFilter -> ContextFilter -> TraceFilter -> TimeoutFilter -> MonitorFilter -> ExceptionFilter -> AbstractProxyInvoker
消费者最终生成链路:
ConsumerContextFilter -> FutureFilter -> MonitorFilter -> GenericImplFilter -> DubboInvoker
参考调用拦截扩展: https://dubbo.apache.org/zh/docs/references/spis/filter/
4. GenericFilter & GenericImplFilter
我们在生产者链路看到GenericFilter过滤器,消费者链路看到GenericImplFilter过滤器,正是这两个过滤器实现了泛化调用的核心转换。
GenericImplFilter:
@Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000)
public class GenericImplFilter implements Filter, Filter.Listener {
@Override
public Result invoke(Invoker> invoker, Invocation invocation) throws RpcException {
String generic = invoker.getUrl().getParameter(GENERIC_KEY); //true
// ProtocolUtils.isGeneric(generic) && (MethodName!=$invoke || $invokeAsync) && invocation instanceof RpcInvocation
if (isCallingGenericImpl(generic, invocation)) {
RpcInvocation invocation2 = new RpcInvocation(invocation);
//非泛化调用逻辑省略 (PojoUtils序列化)
......
invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);
invocation2.setParameterTypesDesc(GENERIC_PARAMETER_DESC);
invocation2.setArguments(new Object[]{methodName, types, args});
return invoker.invoke(invocation2);
}
//泛化调用判断 ProtocolUtils.isGeneric(generic) && (MethodName==$invoke || $invokeAsync) && invocation.getArguments().length == 3
else if (isMakingGenericCall(generic, invocation)) {
//参数值
Object[] args = (Object[]) invocation.getArguments()[2];
//非泛化调用 "nativejava"==generic || "bean"==generic 的异常判断,逻辑省略
......
//把泛化标识放到invocation的attachment内,上送给provider端
invocation.setAttachment(
GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY));
}
//继续执行
return invoker.invoke(invocation);
}
}
GenericFilter:
@Activate(group = CommonConstants.PROVIDER, order = -20000)
public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware {
@Override
public Result invoke(Invoker> invoker, Invocation inv) throws RpcException {
//泛化调用判断
if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC))
&& inv.getArguments() != null
&& inv.getArguments().length == 3
&& !GenericService.class.isAssignableFrom(invoker.getInterface())) {
//方法名、参数类型 、参数值
String name = ((String) inv.getArguments()[0]).trim();
String[] types = (String[]) inv.getArguments()[1];
Object[] args = (Object[]) inv.getArguments()[2];
try {
Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);
Class>[] params = method.getParameterTypes();
//参数判断
if (args == null) {
args = new Object[params.length];
}
if(types == null) {
types = new String[params.length];
}
if (args.length != types.length) {
throw new RpcException("GenericFilter#invoke args.length != types.length, please check your "
+ "params");
}
//消费端设置的为true
String generic = inv.getAttachment(GENERIC_KEY);
//其它协议的逻辑 忽略
......
//构建rpcInvocation对象
RpcInvocation rpcInvocation = new RpcInvocation(inv.getTargetServiceUniqueName(),
invoker.getUrl().getServiceModel(), method.getName(), invoker.getInterface().getName(), invoker.getUrl().getProtocolServiceKey(),
method.getParameterTypes(), args, inv.getObjectAttachments(),
inv.getInvoker(), inv.getAttributes(), inv instanceof RpcInvocation ? ((RpcInvocation) inv).getInvokeMode() : null);
return invoker.invoke(rpcInvocation);
} catch (NoSuchMethodException | ClassNotFoundException e) {
throw new RpcException(e.getMessage(), e);
}
}
return invoker.invoke(inv);
}
}
应用场景:
- 通用化的测试平台
- 搭配网关使用
我们要搭建一个轻量级的服务网关,可以让各个业务方用HTTP的方式,通过服务网关调用其它服务。服务网关要作为所有RPC服务的调用端。
通常我们有两种方案:1.引入所有服务提供方的接口API 2.泛化调用。 - 自由发挥
隐式参数传递
dubbo中有attachments机制, 用于在业务请求之外传递附加信息, 可以理解为类似http的报文头可传递附加信息。常用于服务鉴权,公共参数传递。
服务提供方使用RpcContext.getContext().getAttachments();获取参数,服务器消费方使用RpcContext.getContext().setAttachment(); 传递参数。
服务提供方通过 ContextFilter将收到的 RpcInvocation 中的参数设置到 RpcContext中去。



