性能文章>源码分析Dubbo 泛化调用与泛化实现原理>

源码分析Dubbo 泛化调用与泛化实现原理原创

1年前
223845

本文将重点分析Dubbo的两个重要特性:泛化调用与泛化实现。

泛化引用:

image1.jpeg

通常是服务调用方没有引入API包,也就不包含接口中的实体类,故服务调用方只能提供Map形式的数据,由服务提供者根据Map转化成对应的实体。
泛化实现

image2.jpeg

泛化实现,是指服务提供者未引入API包,也就不包含接口用于传输数据的实体类,故客户端发起调用前,需要将mode转化为Map。
从上面分析,其实所谓的泛化本质上就是Map与Bean的转换。

GenericImplFilter实现原理

  1public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
  2        String generic = invoker.getUrl().getParameter(Constants.GENERIC_KEY);
  3        if (ProtocolUtils.isGeneric(generic)                                                                                  // @1
  4                && !Constants.$INVOKE.equals(invocation.getMethodName())
  5                && invocation instanceof RpcInvocation) {
  6            RpcInvocation invocation2 = (RpcInvocation) invocation;
  7            String methodName = invocation2.getMethodName();
  8            Class<?>[] parameterTypes = invocation2.getParameterTypes();
  9            Object[] arguments = invocation2.getArguments();
 10
 11            String[] types = new String[parameterTypes.length];
 12            for (int i = 0; i < parameterTypes.length; i++) {
 13                types[i] = ReflectUtils.getName(parameterTypes[i]);
 14            }
 15
 16            Object[] args;
 17            if (ProtocolUtils.isBeanGenericSerialization(generic)) {
 18                args = new Object[arguments.length];
 19                for (int i = 0; i < arguments.length; i++) {
 20                    args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD);
 21                }
 22            } else {
 23                args = PojoUtils.generalize(arguments);
 24            }
 25
 26            invocation2.setMethodName(Constants.$INVOKE);
 27            invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);
 28            invocation2.setArguments(new Object[]{methodName, types, args});
 29            Result result = invoker.invoke(invocation2);
 30
 31            if (!result.hasException()) {
 32                Object value = result.getValue();
 33                try {
 34                    Method method = invoker.getInterface().getMethod(methodName, parameterTypes);
 35                    if (ProtocolUtils.isBeanGenericSerialization(generic)) {
 36                        if (value == null) {
 37                            return new RpcResult(value);
 38                        } else if (value instanceof JavaBeanDescriptor) {
 39                            return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value));
 40                        } else {
 41                            throw new RpcException(
 42                                    "The type of result value is " +
 43                                            value.getClass().getName() +
 44                                            " other than " +
 45                                            JavaBeanDescriptor.class.getName() +
 46                                            ", and the result is " +
 47                                            value);
 48                        }
 49                    } else {
 50                        return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType()));
 51                    }
 52                } catch (NoSuchMethodException e) {
 53                    throw new RpcException(e.getMessage(), e);
 54                }
 55            } else if (result.getException() instanceof GenericException) {
 56                GenericException exception = (GenericException) result.getException();
 57                try {
 58                    String className = exception.getExceptionClass();
 59                    Class<?> clazz = ReflectUtils.forName(className);
 60                    Throwable targetException = null;
 61                    Throwable lastException = null;
 62                    try {
 63                        targetException = (Throwable) clazz.newInstance();
 64                    } catch (Throwable e) {
 65                        lastException = e;
 66                        for (Constructor<?> constructor : clazz.getConstructors()) {
 67                            try {
 68                                targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]);
 69                                break;
 70                            } catch (Throwable e1) {
 71                                lastException = e1;
 72                            }
 73                        }
 74                    }
 75                    if (targetException != null) {
 76                        try {
 77                            Field field = Throwable.class.getDeclaredField("detailMessage");
 78                            if (!field.isAccessible()) {
 79                                field.setAccessible(true);
 80                            }
 81                            field.set(targetException, exception.getExceptionMessage());
 82                        } catch (Throwable e) {
 83                            logger.warn(e.getMessage(), e);
 84                        }
 85                        result = new RpcResult(targetException);
 86                    } else if (lastException != null) {
 87                        throw lastException;
 88                    }
 89                } catch (Throwable e) {
 90                    throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e);
 91                }
 92            }
 93            return result;
 94        }
 95
 96        if (invocation.getMethodName().equals(Constants.$INVOKE)                             // @2
 97                && invocation.getArguments() != null
 98                && invocation.getArguments().length == 3
 99                && ProtocolUtils.isGeneric(generic)) {
100
101            Object[] args = (Object[]) invocation.getArguments()[2];
102            if (ProtocolUtils.isJavaGenericSerialization(generic)) {
103
104                for (Object arg : args) {
105                    if (!(byte[].class == arg.getClass())) {
106                        error(byte[].class.getName(), arg.getClass().getName());
107                    }
108                }
109            } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
110                for (Object arg : args) {
111                    if (!(arg instanceof JavaBeanDescriptor)) {
112                        error(JavaBeanDescriptor.class.getName(), arg.getClass().getName());
113                    }
114                }
115            }
116
117            ((RpcInvocation) invocation).setAttachment(
118                    Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY));
119        }
120        return invoker.invoke(invocation);
121    }
  • 代码@1:该分支是泛化实现,如果是泛化实现,则根据generic的值进行序列化,然后调用$invoke方法,因为服务端实现为泛化实现,所有的服务提供者实现GenericeServer#$invoker方法,其实现方式就是将Bean转换成Map。这些细节将在服务端GenericFilter序列中详细讲解。

  • 代码@2:泛化引用,调用方是直接通过GenericService#$invoke方法进行调用,以此来区分是泛化调用还是泛化引用,那不经要问,为什么invoker.getUrl().getParameter(Constants.GENERIC_KEY)中获取的generic参数到底是< dubbo:service/>中配置的还是< dubbo:reference/>中配置的呢?其实不难理解:

  • dubbo:servcie未配置而dubbo:reference配置了,则代表的是消费端的,必然是泛化引用。

  • dubbo:servcie配置而dubbo:reference未配置了,则代表的是服务端的,必然是泛化实现。

如果两者都配置了,generic以消费端为主。消费端参数与服务端参数的合并在服务发现时,注册中心首先会将服务提供者的URL通知消费端,然后消费端会使用当前的配置与服务提供者URL中的配置进行合并,如遇到相同参数,则消费端覆盖服务端。
注:这里我就不深入去探讨其实现细节,因为这部分在下文源码分析GenericFilter时会详细介绍Map与Bean转换的细节,包含是否序列化,之所以这里没有细说,主要是因为我先看的是GenericFilter。

GenericFilter实现原理

 1@Activate(group = Constants.PROVIDER, order = -20000)
 2public class GenericFilter implements Filter {
 3    @Override
 4    public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
 5        if (inv.getMethodName().equals(Constants.$INVOKE)
 6                && inv.getArguments() != null
 7                && inv.getArguments().length == 3
 8                && !ProtocolUtils.isGeneric(invoker.getUrl().getParameter(Constants.GENERIC_KEY))) {       // @1
 9            String name = ((String) inv.getArguments()[0]).trim();
10            String[] types = (String[]) inv.getArguments()[1];
11            Object[] args = (Object[]) inv.getArguments()[2];
12            try {
13                Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);             // @2
14                Class<?>[] params = method.getParameterTypes();
15                if (args == null) {
16                    args = new Object[params.length];
17                }
18                String generic = inv.getAttachment(Constants.GENERIC_KEY);
19                if (StringUtils.isEmpty(generic)
20                        || ProtocolUtils.isDefaultGenericSerialization(generic)) {                                                             // @3
21                    args = PojoUtils.realize(args, params, method.getGenericParameterTypes());
22                } else if (ProtocolUtils.isJavaGenericSerialization(generic)) {                                                             // @4
23                    for (int i = 0; i < args.length; i++) {
24                        if (byte[].class == args[i].getClass()) {
25                            try {
26                                UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i]);
27                                args[i] = ExtensionLoader.getExtensionLoader(Serialization.class)
28                                        .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
29                                        .deserialize(null, is).readObject();
30                            } catch (Exception e) {
31                                throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e);
32                            }
33                        } else {
34                            throw new RpcException(
35                                    "Generic serialization [" +
36                                            Constants.GENERIC_SERIALIZATION_NATIVE_JAVA +
37                                            "] only support message type " +
38                                            byte[].class +
39                                            " and your message type is " +
40                                            args[i].getClass());
41                        }
42                    }
43                } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {                                                 // @5
44                    for (int i = 0; i < args.length; i++) {
45                        if (args[i] instanceof JavaBeanDescriptor) {
46                            args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);
47                        } else {
48                            throw new RpcException(
49                                    "Generic serialization [" +
50                                            Constants.GENERIC_SERIALIZATION_BEAN +
51                                            "] only support message type " +
52                                            JavaBeanDescriptor.class.getName() +
53                                            " and your message type is " +
54                                            args[i].getClass().getName());
55                        }
56                    }
57                }
58                Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));    // @6
59                if (result.hasException()
60                        && !(result.getException() instanceof GenericException)) {
61                    return new RpcResult(new GenericException(result.getException()));
62                }
63                if (ProtocolUtils.isJavaGenericSerialization(generic)) {                                                        // @7
64                    try {
65                        UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512);
66                        ExtensionLoader.getExtensionLoader(Serialization.class)
67                                .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
68                                .serialize(null, os).writeObject(result.getValue());
69                        return new RpcResult(os.toByteArray());
70                    } catch (IOException e) {
71                        throw new RpcException("Serialize result failed.", e);
72                    }
73                } else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
74                    return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD));
75                } else {
76                    return new RpcResult(PojoUtils.generalize(result.getValue()));
77                }
78            } catch (NoSuchMethodException e) {
79                throw new RpcException(e.getMessage(), e);
80            } catch (ClassNotFoundException e) {
81                throw new RpcException(e.getMessage(), e);
82            }
83        }
84        return invoker.invoke(inv);  
85    }
86}
  • 代码@1:如果方法名为$invoker,并且只有3个参数,并且服务端实现为非返回实现,则认为本次服务调用时客户端泛化引用服务端,客户端的泛化调用,需要将请求参数反序列化为该接口真实的pojo对象。
  • 代码@2:根据接口名(API类)、方法名、方法参数类型列表,根据反射机制获取对应的方法。
  • 代码@3:处理普通的泛化引用调用,即处理,只需要将参数列表Object[]反序列化为pojo即可,具体的反序列化为PojoUtils#realize,其实现原理如下:

在JAVA的世界中,pojo通常用map来表示,也就是一个Map可以用来表示一个对象的值,那从一个Map如果序列化一个对象呢?其关键的要素是要在Map中保留该对象的类路径名。例如现在有这样一个对象:

 1public class Student {
 2    private int id;
 3    private String name;
 4    private Team team;
 5    //省略get set方法
 6}
 7public class Team {
 8    private int id;
 9    private String name;
10    // 省略其他属性与set get方法
11}
12用Map表示Student为:
13{
14    “class”:"somepackeage.Student",
15    "id":1,
16    "name":"dingw",
17    "team":
18    {
19        "class" : "somepackage.Team",
20        "id":2,
21        "name":"t"
22    }
23}

也就是通过class来标识该Map需要反序列化的pojo类型。

  • 代码@4:处理< dubbo:reference generic=“nativejava” /> 启用泛化引用,并使用nativejava序列化参数,在服务端这边通过nativejava反序列化参数成pojo对象。
  • 代码@5:处理< dubbo:reference generic=“bean” /> 启用泛化引用,并使用javabean序列化参数,在服务端这边通过javabean反序列化参数成pojo对象。
  • 代码@6:序列化API方法中声明的类型,构建new RpcInvocation(method, args, inv.getAttachments())调用环境,继续调用后续过滤器。
  • 代码@7:处理执行结果,如果是nativejava或bean,则需要对返回结果序列化,如果是generic=true,则使用PojoUtils.generalize序列化,也即将pojo序列化为Map。

泛化调用与泛化引用,就介绍到这里了。

点赞收藏
丁威
请先登录,查看4条精彩评论吧
快去登录吧,你将获得
  • 浏览更多精彩评论
  • 和开发者讨论交流,共同进步
5
4