远程调用

InvokerInvocationHandler.java

  1. public InvokerInvocationHandler(Invoker<?> handler) {
  2. this.invoker = handler;
  3. }
  4. @Override
  5. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  6. // 获取到RPC远程调用的方法名
  7. String methodName = method.getName();
  8. Class<?>[] parameterTypes = method.getParameterTypes();
  9. // 若当前方法为Object的方法,则为本地方法调用
  10. if (method.getDeclaringClass() == Object.class) {
  11. return method.invoke(invoker, args);
  12. }
  13. if ("toString".equals(methodName) && parameterTypes.length == 0) {
  14. return invoker.toString();
  15. }
  16. if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
  17. return invoker.hashCode();
  18. }
  19. if ("equals".equals(methodName) && parameterTypes.length == 1) {
  20. return invoker.equals(args[0]);
  21. }
  22. // 远程调用。此处创建出来的是MockClusterInvoker。
  23. // 而MockClusterInvoker是在上次源代码分析中ReferenceConfig.java中createProxy()创建代理对象中
  24. // invoker = CLUSTER.join(new StaticDirectory(u, invokers));这行代码创建出来的
  25. return invoker.invoke(new RpcInvocation(method, args)).recreate();
  26. }

MockClusterInvoker.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. Result result = null;
  3. // 获取mock属性值
  4. String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim();
  5. // 若没有设置mock属性,或mock属性值为false,则不具有降级功能
  6. if (value.length() == 0 || value.equalsIgnoreCase("false")) {
  7. //no mock 远程调用(不会降级)
  8. result = this.invoker.invoke(invocation);
  9. } else if (value.startsWith("force")) {
  10. if (logger.isWarnEnabled()) {
  11. logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
  12. }
  13. //force:direct mock 直接降级
  14. result = doMockInvoke(invocation, null);
  15. } else {
  16. //fail-mock
  17. try { // 远程调用
  18. result = this.invoker.invoke(invocation);
  19. } catch (RpcException e) {
  20. if (e.isBiz()) {
  21. throw e;
  22. }
  23. if (logger.isWarnEnabled()) {
  24. logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
  25. }
  26. // 服务降级
  27. result = doMockInvoke(invocation, e);
  28. }
  29. }
  30. return result;
  31. }

AbstractClusterInvoker.java

  1. public Result invoke(final Invocation invocation) throws RpcException {
  2. checkWhetherDestroyed();
  3. // binding attachments into invocation.
  4. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
  5. if (contextAttachments != null && contextAttachments.size() != 0) {
  6. ((RpcInvocation) invocation).addAttachments(contextAttachments);
  7. }
  8. // 路由:根据路由规则过滤掉不可用的invoker,返回剩下的可用的invoker
  9. List<Invoker<T>> invokers = list(invocation);
  10. // 获取负载均衡策略
  11. LoadBalance loadbalance = initLoadBalance(invokers, invocation);
  12. RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
  13. // 调用具体容错策略的doInvoke()
  14. return doInvoke(invocation, invokers, loadbalance);
  15. }

FailoverClusterInvoker.java

  1. public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
  2. List<Invoker<T>> copyInvokers = invokers;
  3. checkInvokers(copyInvokers, invocation);
  4. String methodName = RpcUtils.getMethodName(invocation);
  5. int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
  6. if (len <= 0) {
  7. len = 1;
  8. }
  9. // retry loop.
  10. RpcException le = null; // last exception.
  11. List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
  12. Set<String> providers = new HashSet<String>(len);
  13. for (int i = 0; i < len; i++) {
  14. //Reselect before retry to avoid a change of candidate `invokers`.
  15. //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
  16. if (i > 0) {
  17. checkWhetherDestroyed();
  18. copyInvokers = list(invocation);
  19. // check again
  20. checkInvokers(copyInvokers, invocation);
  21. } // 负载均衡
  22. Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
  23. invoked.add(invoker);
  24. RpcContext.getContext().setInvokers((List) invoked);
  25. try { // 远程调用
  26. Result result = invoker.invoke(invocation);
  27. if (le != null && logger.isWarnEnabled()) {
  28. logger.warn("Although retry the method " + methodName
  29. + " in the service " + getInterface().getName()
  30. + " was successful by the provider " + invoker.getUrl().getAddress()
  31. + ", but there have been failed providers " + providers
  32. + " (" + providers.size() + "/" + copyInvokers.size()
  33. + ") from the registry " + directory.getUrl().getAddress()
  34. + " on the consumer " + NetUtils.getLocalHost()
  35. + " using the dubbo version " + Version.getVersion() + ". Last error is: "
  36. + le.getMessage(), le);
  37. }
  38. return result;
  39. } catch (RpcException e) {
  40. if (e.isBiz()) { // biz exception.
  41. throw e;
  42. }
  43. le = e;
  44. } catch (Throwable e) {
  45. le = new RpcException(e.getMessage(), e);
  46. } finally {
  47. providers.add(invoker.getUrl().getAddress());
  48. }
  49. }
  50. throw new RpcException(le.getCode(), "Failed to invoke the method "
  51. + methodName + " in the service " + getInterface().getName()
  52. + ". Tried " + len + " times of the providers " + providers
  53. + " (" + providers.size() + "/" + copyInvokers.size()
  54. + ") from the registry " + directory.getUrl().getAddress()
  55. + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
  56. + Version.getVersion() + ". Last error is: "
  57. + le.getMessage(), le.getCause() != null ? le.getCause() : le);
  58. }

ProtocolFilterWrapper.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. Result asyncResult = filterInvoker.invoke(invocation); // 返回一个异步结果
  3. asyncResult = asyncResult.whenCompleteWithContext((r, t) -> {
  4. for (int i = filters.size() - 1; i >= 0; i--) {
  5. Filter filter = filters.get(i);
  6. // onResponse callback
  7. if (filter instanceof ListenableFilter) {
  8. Filter.Listener listener = ((ListenableFilter) filter).listener();
  9. if (listener != null) {
  10. if (t == null) {
  11. listener.onResponse(r, filterInvoker, invocation);
  12. } else {
  13. listener.onError(t, filterInvoker, invocation);
  14. }
  15. }
  16. } else {
  17. filter.onResponse(r, filterInvoker, invocation);
  18. }
  19. }
  20. });
  21. return asyncResult;
  22. }
  23. public Result invoke(Invocation invocation) throws RpcException {
  24. Result asyncResult;
  25. try {
  26. // 继续追这里
  27. asyncResult = filter.invoke(next, invocation);
  28. } catch (Exception e) {
  29. // onError callback
  30. if (filter instanceof ListenableFilter) {
  31. Filter.Listener listener = ((ListenableFilter) filter).listener();
  32. if (listener != null) {
  33. listener.onError(e, invoker, invocation);
  34. }
  35. }
  36. throw e;
  37. }
  38. return asyncResult;
  39. }

MonitorFilter.java

  1. public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
  2. if (invoker.getUrl().hasParameter(MONITOR_KEY)) {
  3. invocation.setAttachment(MONITOR_FILTER_START_TIME, String.valueOf(System.currentTimeMillis()));
  4. getConcurrent(invoker, invocation).incrementAndGet(); // count up
  5. }
  6. return invoker.invoke(invocation); // proceed invocation chain
  7. }

ListenerInvokerWrapper.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. return invoker.invoke(invocation);
  3. }

AsyncToSyncInvoker.java

  1. public Result invoke(Invocation invocation) throws RpcException {
  2. Result asyncResult = invoker.invoke(invocation);
  3. try {
  4. if (InvokeMode.SYNC == ((RpcInvocation) invocation).getInvokeMode()) {
  5. asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
  6. }
  7. } catch (InterruptedException e) {
  8. throw new RpcException("Interrupted unexpectedly while waiting for remoting result to return! method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
  9. } catch (ExecutionException e) {
  10. Throwable t = e.getCause();
  11. if (t instanceof TimeoutException) {
  12. throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
  13. } else if (t instanceof RemotingException) {
  14. throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
  15. }
  16. } catch (Throwable e) {
  17. throw new RpcException(e.getMessage(), e);
  18. }
  19. return asyncResult;
  20. }

AbstractInvoker.java

  1. public Result invoke(Invocation inv) throws RpcException {
  2. // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed
  3. if (destroyed.get()) {
  4. logger.warn("Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, "
  5. + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer");
  6. }
  7. RpcInvocation invocation = (RpcInvocation) inv;
  8. invocation.setInvoker(this);
  9. if (CollectionUtils.isNotEmptyMap(attachment)) {
  10. invocation.addAttachmentsIfAbsent(attachment);
  11. }
  12. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
  13. if (CollectionUtils.isNotEmptyMap(contextAttachments)) {
  14. /**
  15. * invocation.addAttachmentsIfAbsent(context){@link RpcInvocation#addAttachmentsIfAbsent(Map)}should not be used here,
  16. * because the {@link RpcContext#setAttachment(String, String)} is passed in the Filter when the call is triggered
  17. * by the built-in retry mechanism of the Dubbo. The attachment to update RpcContext will no longer work, which is
  18. * a mistake in most cases (for example, through Filter to RpcContext output traceId and spanId and other information).
  19. */
  20. invocation.addAttachments(contextAttachments);
  21. }
  22. invocation.setInvokeMode(RpcUtils.getInvokeMode(url, invocation));
  23. RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
  24. try {
  25. //跟这里
  26. return doInvoke(invocation); //
  27. } catch (InvocationTargetException e) { // biz exception
  28. Throwable te = e.getTargetException();
  29. if (te == null) {
  30. return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation);
  31. } else {
  32. if (te instanceof RpcException) {
  33. ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION);
  34. }
  35. return AsyncRpcResult.newDefaultAsyncResult(null, te, invocation);
  36. }
  37. } catch (RpcException e) {
  38. if (e.isBiz()) {
  39. return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation);
  40. } else {
  41. throw e;
  42. }
  43. } catch (Throwable e) {
  44. return AsyncRpcResult.newDefaultAsyncResult(null, e, invocation);
  45. }
  46. }

DubboInvoker.java

  1. protected Result doInvoke(final Invocation invocation) throws Throwable {
  2. RpcInvocation inv = (RpcInvocation) invocation;
  3. final String methodName = RpcUtils.getMethodName(invocation);
  4. inv.setAttachment(PATH_KEY, getUrl().getPath());
  5. inv.setAttachment(VERSION_KEY, version);
  6. ExchangeClient currentClient;
  7. // clients是一个ExchangeClient数组,若只有一个ExchangeClient,则直接返回,否则通过轮询方式返回一个
  8. if (clients.length == 1) {
  9. currentClient = clients[0];
  10. } else { // 轮询返回一个exchangeClient
  11. currentClient = clients[index.getAndIncrement() % clients.length];
  12. }
  13. try { // 若一个请求无需响应,则isOneway为true,表示单向的
  14. boolean isOneway = RpcUtils.isOneway(getUrl(), invocation);
  15. int timeout = getUrl().getMethodPositiveParameter(methodName, TIMEOUT_KEY, DEFAULT_TIMEOUT);
  16. if (isOneway) {
  17. boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false);
  18. currentClient.send(inv, isSent);
  19. return AsyncRpcResult.newDefaultAsyncResult(invocation);
  20. } else {
  21. AsyncRpcResult asyncRpcResult = new AsyncRpcResult(inv);
  22. // 通过同异步转换对象currentClient发送请求
  23. CompletableFuture<Object> responseFuture = currentClient.request(inv, timeout);
  24. asyncRpcResult.subscribeTo(responseFuture);
  25. // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter
  26. FutureContext.getContext().setCompatibleFuture(responseFuture);
  27. return asyncRpcResult;
  28. }
  29. } catch (TimeoutException e) {
  30. throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
  31. } catch (RemotingException e) {
  32. throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
  33. }
  34. }

ReferenceCountExchangeClient.java

  1. public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException {
  2. return client.request(request, timeout);
  3. }

HeaderExchangeClient.java

  1. public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException {
  2. return channel.request(request, timeout);
  3. }

HeaderExchangeChannel.java

  1. public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException {
  2. if (closed) {
  3. throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!");
  4. }
  5. // create request.
  6. Request req = new Request();
  7. req.setVersion(Version.getProtocolVersion());
  8. req.setTwoWay(true);
  9. req.setData(request);
  10. DefaultFuture future = DefaultFuture.newFuture(channel, req, timeout);
  11. try {
  12. channel.send(req); // 发送请求
  13. } catch (RemotingException e) {
  14. future.cancel();
  15. throw e;
  16. }
  17. return future;
  18. }

AbstractPeer.java

  1. public void send(Object message) throws RemotingException {
  2. send(message, url.getParameter(Constants.SENT_KEY, false));
  3. }

AbstractClient.java

  1. public void send(Object message, boolean sent) throws RemotingException {
  2. if (needReconnect && !isConnected()) {
  3. connect(); // 连接Server
  4. }
  5. Channel channel = getChannel();
  6. //TODO Can the value returned by getChannel() be null? need improvement.
  7. if (channel == null || !channel.isConnected()) {
  8. throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
  9. }
  10. channel.send(message, sent); // 发送请求
  11. }

NettyChannel.java

  1. public void send(Object message, boolean sent) throws RemotingException {
  2. // whether the channel is closed
  3. super.send(message, sent);
  4. boolean success = true;
  5. int timeout = 0;
  6. try {
  7. ChannelFuture future = channel.writeAndFlush(message); // 向Server发送数据
  8. if (sent) {
  9. // wait timeout ms
  10. timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
  11. success = future.await(timeout);
  12. }
  13. Throwable cause = future.cause();
  14. if (cause != null) {
  15. throw cause;
  16. }
  17. } catch (Throwable e) {
  18. throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e);
  19. }
  20. if (!success) {
  21. throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
  22. + "in timeout(" + timeout + "ms) limit");
  23. }
  24. }

提供者处理消费者请求

NettyServer.java

  1. protected void doOpen() throws Throwable {
  2. bootstrap = new ServerBootstrap();
  3. // 处理连接的Group
  4. bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
  5. // 处理IO业务的Group
  6. workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
  7. new DefaultThreadFactory("NettyServerWorker", true));
  8. //提供者的URL
  9. final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
  10. channels = nettyServerHandler.getChannels();
  11. bootstrap.group(bossGroup, workerGroup)
  12. .channel(NioServerSocketChannel.class)
  13. .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
  14. .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
  15. .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
  16. .childHandler(new ChannelInitializer<NioSocketChannel>() {
  17. @Override
  18. protected void initChannel(NioSocketChannel ch) throws Exception {
  19. // FIXME: should we use getTimeout()?
  20. int idleTimeout = UrlUtils.getIdleTimeout(getUrl());
  21. NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
  22. ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
  23. // 解码器
  24. .addLast("decoder", adapter.getDecoder())
  25. // 编码器
  26. .addLast("encoder", adapter.getEncoder())
  27. // 读写空闲监测
  28. .addLast("server-idle-handler", new IdleStateHandler(0, 0, idleTimeout, MILLISECONDS))
  29. // Dubbo的自定义处理器
  30. .addLast("handler", nettyServerHandler);
  31. }
  32. });
  33. // bind
  34. ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
  35. channelFuture.syncUninterruptibly();
  36. channel = channelFuture.channel();
  37. }

NettyServerHandler.java

  1. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  2. NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
  3. try {
  4. // 这块再跟下去就是Netty底层了。
  5. handler.received(channel, msg);
  6. } finally {
  7. NettyChannel.removeChannelIfDisconnected(ctx.channel());
  8. }
  9. }

AllChannelHandler.java

  1. public void received(Channel channel, Object message) throws RemotingException {
  2. ExecutorService executor = getExecutorService(); // 线程池
  3. try { // 将Client发送来处数据包装为一个任务,使用线程池中的线程来完成
  4. executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
  5. } catch (Throwable t) {
  6. //TODO A temporary solution to the problem that the exception information can not be sent to the opposite end after the thread pool is full. Need a refactoring
  7. //fix The thread pool is full, refuses to call, does not return, and causes the consumer to wait for time out
  8. if(message instanceof Request && t instanceof RejectedExecutionException){
  9. Request request = (Request)message;
  10. if(request.isTwoWay()){
  11. String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") threadpool is exhausted ,detail msg:" + t.getMessage();
  12. Response response = new Response(request.getId(), request.getVersion());
  13. response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
  14. response.setErrorMessage(msg);
  15. channel.send(response);
  16. return;
  17. }
  18. }
  19. throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
  20. }
  21. }

ChannelEventRunnable.java

  1. public void run() {
  2. // 接收到处理任务
  3. if (state == ChannelState.RECEIVED) {
  4. try {
  5. handler.received(channel, message);
  6. } catch (Exception e) {
  7. logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel
  8. + ", message is " + message, e);
  9. }
  10. }
  11. ......
  12. }

DecodeHandler.java

  1. // 接下来对数据进行解码,然后对数据进行解析然后处理消费者的请求
  2. public void received(Channel channel, Object message) throws RemotingException {
  3. if (message instanceof Decodeable) {
  4. decode(message); // 解码消息
  5. }
  6. if (message instanceof Request) {
  7. decode(((Request) message).getData()); // 解码RpcInvocation
  8. }
  9. if (message instanceof Response) {
  10. decode(((Response) message).getResult()); // 解码响应结果
  11. }
  12. // 此时的message是经过解码的
  13. handler.received(channel, message);
  14. }

HeaderExchangeHandler.java

  1. public void received(Channel channel, Object message) throws RemotingException {
  2. channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis());
  3. final ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel);
  4. try {
  5. if (message instanceof Request) { // 处理message为请求的情况
  6. // handle request.
  7. Request request = (Request) message;
  8. if (request.isEvent()) {
  9. handlerEvent(channel, request);
  10. } else {
  11. if (request.isTwoWay()) {
  12. handleRequest(exchangeChannel, request); // 处理请求
  13. } else {
  14. handler.received(exchangeChannel, request.getData());
  15. }
  16. }
  17. } else if (message instanceof Response) { // 处理message为响应的情况
  18. handleResponse(channel, (Response) message);
  19. } else if (message instanceof String) {
  20. if (isClientSide(channel)) {
  21. Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl());
  22. logger.error(e.getMessage(), e);
  23. } else {
  24. String echo = handler.telnet(channel, (String) message);
  25. if (echo != null && echo.length() > 0) {
  26. channel.send(echo);
  27. }
  28. }
  29. } else {
  30. handler.received(exchangeChannel, message);
  31. }
  32. } finally {
  33. HeaderExchangeChannel.removeChannelIfDisconnected(channel);
  34. }
  35. }
  36. void handleRequest(final ExchangeChannel channel, Request req) throws RemotingException {
  37. Response res = new Response(req.getId(), req.getVersion());
  38. if (req.isBroken()) { // 若请求过程中发生了异常,则在这里处理
  39. Object data = req.getData();
  40. String msg;
  41. if (data == null) {
  42. msg = null;
  43. } else if (data instanceof Throwable) {
  44. msg = StringUtils.toString((Throwable) data);
  45. } else {
  46. msg = data.toString();
  47. }
  48. res.setErrorMessage("Fail to decode request due to: " + msg);
  49. res.setStatus(Response.BAD_REQUEST);
  50. channel.send(res); // 将包含有异常信息的响应返回
  51. return;
  52. }
  53. // find handler by message class.
  54. Object msg = req.getData(); // 获取RpcInvocation
  55. try {
  56. CompletionStage<Object> future = handler.reply(channel, msg);
  57. future.whenComplete((appResult, t) -> {
  58. try {
  59. if (t == null) {
  60. res.setStatus(Response.OK);
  61. res.setResult(appResult);
  62. } else {
  63. res.setStatus(Response.SERVICE_ERROR);
  64. res.setErrorMessage(StringUtils.toString(t));
  65. }
  66. channel.send(res); // 将真正的响应结果返回
  67. } catch (RemotingException e) {
  68. logger.warn("Send result to consumer failed, channel is " + channel + ", msg is " + e);
  69. } finally {
  70. // HeaderExchangeChannel.removeChannelIfDisconnected(channel);
  71. }
  72. });
  73. } catch (Throwable e) {
  74. res.setStatus(Response.SERVICE_ERROR);
  75. res.setErrorMessage(StringUtils.toString(e));
  76. channel.send(res);
  77. }
  78. }

DubboProtocol.java

  1. @Override
  2. public CompletableFuture<Object> reply(ExchangeChannel channel, Object message) throws RemotingException {
  3. if (!(message instanceof Invocation)) {
  4. throw new RemotingException(channel, "Unsupported request: "
  5. + (message == null ? null : (message.getClass().getName() + ": " + message))
  6. + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress());
  7. }
  8. Invocation inv = (Invocation) message;
  9. Invoker<?> invoker = getInvoker(channel, inv); // 获取到invoker
  10. // need to consider backward-compatibility if it's a callback
  11. if (Boolean.TRUE.toString().equals(inv.getAttachments().get(IS_CALLBACK_SERVICE_INVOKE))) {
  12. String methodsStr = invoker.getUrl().getParameters().get("methods");
  13. boolean hasMethod = false;
  14. if (methodsStr == null || !methodsStr.contains(",")) {
  15. hasMethod = inv.getMethodName().equals(methodsStr);
  16. } else {
  17. String[] methods = methodsStr.split(",");
  18. for (String method : methods) {
  19. if (inv.getMethodName().equals(method)) {
  20. hasMethod = true;
  21. break;
  22. }
  23. }
  24. }
  25. if (!hasMethod) {
  26. logger.warn(new IllegalStateException("The methodName " + inv.getMethodName()
  27. + " not found in callback service interface ,invoke will be ignored."
  28. + " please update the api interface. url is:"
  29. + invoker.getUrl()) + " ,invocation is :" + inv);
  30. return null;
  31. }
  32. }
  33. RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress());
  34. Result result = invoker.invoke(inv); // 进行本地调用并获得一个Result结果
  35. return result.completionFuture().thenApply(Function.identity());
  36. }

消费者处理提供者响应

NettyClientHandler.java

  1. // 消费者收到提供者的响应,首先会创建一个NettyClinet。创建成功后会执行到channelRead方法,我们从这里下手
  2. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  3. NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
  4. try {
  5. handler.received(channel, msg);
  6. } finally {
  7. NettyChannel.removeChannelIfDisconnected(ctx.channel());
  8. }
  9. }

AbstractPeer.java

  1. public void received(Channel ch, Object msg) throws RemotingException {
  2. if (closed) {
  3. return;
  4. }
  5. handler.received(ch, msg);
  6. }

MultiMessageHandler.java

  1. public void received(Channel channel, Object message) throws RemotingException {
  2. if (message instanceof MultiMessage) {
  3. MultiMessage list = (MultiMessage) message;
  4. for (Object obj : list) {
  5. handler.received(channel, obj);
  6. }
  7. } else {
  8. handler.received(channel, message); //
  9. }
  10. }

HeartbeatHandler.java

  1. public void received(Channel channel, Object message) throws RemotingException {
  2. setReadTimestamp(channel);
  3. if (isHeartbeatRequest(message)) { // 判断当前message是否是客户端的心跳
  4. Request req = (Request) message;
  5. if (req.isTwoWay()) {
  6. Response res = new Response(req.getId(), req.getVersion());
  7. res.setEvent(Response.HEARTBEAT_EVENT);
  8. channel.send(res);
  9. if (logger.isInfoEnabled()) {
  10. int heartbeat = channel.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0);
  11. if (logger.isDebugEnabled()) {
  12. logger.debug("Received heartbeat from remote channel " + channel.getRemoteAddress()
  13. + ", cause: The channel has no data-transmission exceeds a heartbeat period"
  14. + (heartbeat > 0 ? ": " + heartbeat + "ms" : ""));
  15. }
  16. }
  17. }
  18. return;
  19. }
  20. if (isHeartbeatResponse(message)) { // 判断当前message是否是来自于Server端的心跳响应
  21. if (logger.isDebugEnabled()) {
  22. logger.debug("Receive heartbeat response in thread " + Thread.currentThread().getName());
  23. }
  24. return;
  25. }
  26. handler.received(channel, message); // message是普通数据
  27. }

AllChannelHandler.java

  1. public void received(Channel channel, Object message) throws RemotingException {
  2. ExecutorService executor = getExecutorService(); // 线程池
  3. try { // 将Client发送来处数据包装为一个任务,使用线程池中的线程来完成
  4. executor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
  5. } catch (Throwable t) {
  6. //TODO A temporary solution to the problem that the exception information can not be sent to the opposite end after the thread pool is full. Need a refactoring
  7. //fix The thread pool is full, refuses to call, does not return, and causes the consumer to wait for time out
  8. if(message instanceof Request && t instanceof RejectedExecutionException){
  9. Request request = (Request)message;
  10. if(request.isTwoWay()){
  11. String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") threadpool is exhausted ,detail msg:" + t.getMessage();
  12. Response response = new Response(request.getId(), request.getVersion());
  13. response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
  14. response.setErrorMessage(msg);
  15. channel.send(response);
  16. return;
  17. }
  18. }
  19. throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
  20. }
  21. }

ChannelEventRunnable.java

  1. public void run() {
  2. // 接收到处理任务
  3. if (state == ChannelState.RECEIVED) {
  4. try {
  5. handler.received(channel, message);
  6. } catch (Exception e) {
  7. logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel
  8. + ", message is " + message, e);
  9. }
  10. }
  11. ......
  12. }

DecodeHandler.java

  1. // 做数据解码
  2. public void received(Channel channel, Object message) throws RemotingException {
  3. if (message instanceof Decodeable) {
  4. decode(message); // 解码消息
  5. }
  6. if (message instanceof Request) {
  7. decode(((Request) message).getData()); // 解码RpcInvocation
  8. }
  9. if (message instanceof Response) {
  10. decode(((Response) message).getResult()); // 解码响应结果
  11. }
  12. // 此时的message是经过解码的
  13. handler.received(channel, message);
  14. }

HeaderExchangeHandler.java

  1. @Override
  2. public void received(Channel channel, Object message) throws RemotingException {
  3. channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis());
  4. final ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel);
  5. try {
  6. if (message instanceof Request) { // 处理message为请求的情况
  7. // handle request.
  8. Request request = (Request) message;
  9. if (request.isEvent()) {
  10. handlerEvent(channel, request);
  11. } else {
  12. if (request.isTwoWay()) {
  13. handleRequest(exchangeChannel, request); // 处理请求
  14. } else {
  15. handler.received(exchangeChannel, request.getData());
  16. }
  17. }
  18. } else if (message instanceof Response) { // 处理message为响应的情况
  19. // 跟踪这里
  20. handleResponse(channel, (Response) message);
  21. } else if (message instanceof String) {
  22. if (isClientSide(channel)) {
  23. Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl());
  24. logger.error(e.getMessage(), e);
  25. } else {
  26. String echo = handler.telnet(channel, (String) message);
  27. if (echo != null && echo.length() > 0) {
  28. channel.send(echo);
  29. }
  30. }
  31. } else {
  32. handler.received(exchangeChannel, message);
  33. }
  34. } finally {
  35. HeaderExchangeChannel.removeChannelIfDisconnected(channel);
  36. }
  37. }
  38. static void handleResponse(Channel channel, Response response) throws RemotingException {
  39. if (response != null && !response.isHeartbeat()) {
  40. DefaultFuture.received(channel, response);
  41. }
  42. }

DefaultFuture.java

  1. public static void received(Channel channel, Response response) {
  2. received(channel, response, false);
  3. }
  4. public static void received(Channel channel, Response response, boolean timeout) {
  5. try {
  6. DefaultFuture future = FUTURES.remove(response.getId());
  7. if (future != null) {
  8. Timeout t = future.timeoutCheckTask;
  9. if (!timeout) {
  10. // decrease Time
  11. t.cancel();
  12. }
  13. // 跟这里
  14. future.doReceived(response);
  15. } else {
  16. logger.warn("The timeout response finally returned at "
  17. + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()))
  18. + ", response " + response
  19. + (channel == null ? "" : ", channel: " + channel.getLocalAddress()
  20. + " -> " + channel.getRemoteAddress()));
  21. }
  22. } finally {
  23. CHANNELS.remove(response.getId());
  24. }
  25. }
  26. private void doReceived(Response res) {
  27. if (res == null) {
  28. throw new IllegalStateException("response cannot be null");
  29. }
  30. if (res.getStatus() == Response.OK) {
  31. // 拿到响应结果并逐层返回
  32. this.complete(res.getResult());
  33. } else if (res.getStatus() == Response.CLIENT_TIMEOUT || res.getStatus() == Response.SERVER_TIMEOUT) {
  34. this.completeExceptionally(new TimeoutException(res.getStatus() == Response.SERVER_TIMEOUT, channel, res.getErrorMessage()));
  35. } else {
  36. this.completeExceptionally(new RemotingException(channel, res.getErrorMessage()));
  37. }
  38. }

CompletableFuture.java

  1. public boolean complete(T value) {
  2. boolean triggered = completeValue(value);
  3. postComplete();
  4. return triggered;
  5. }

ProtocolFilterWrapper.java

  1. // 最终返回到了这里
  2. public Result invoke(Invocation invocation) throws RpcException {
  3. Result asyncResult = filterInvoker.invoke(invocation); // 返回一个异步结果
  4. asyncResult = asyncResult.whenCompleteWithContext((r, t) -> {
  5. for (int i = filters.size() - 1; i >= 0; i--) {
  6. Filter filter = filters.get(i);
  7. // onResponse callback
  8. if (filter instanceof ListenableFilter) {
  9. Filter.Listener listener = ((ListenableFilter) filter).listener();
  10. if (listener != null) {
  11. if (t == null) {
  12. listener.onResponse(r, filterInvoker, invocation);
  13. } else {
  14. listener.onError(t, filterInvoker, invocation);
  15. }
  16. }
  17. } else {
  18. filter.onResponse(r, filterInvoker, invocation);
  19. }
  20. }
  21. });
  22. return asyncResult;
  23. }