同步调用

@param request       请求对象
@param invokeContext 调用上下文
@param timeoutMillis 超时时间（毫秒）
@return 返回对象
@throws RemotingException    远程调用异常
@throws InterruptedException 中断异常
@since 5.2.0
5578
protected SofaResponse doInvokeSync(SofaRequest request, InvokeContext invokeContext, int timeoutMillis)
        throws RemotingException, InterruptedException {
        return (SofaResponse) RPC_CLIENT.invokeSync(url, request, invokeContext, timeoutMillis);
    }
1202647
@RequestMapping(value = "/invoke", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage invoke(HttpServletRequest request, HttpServletResponse response) {
        ResponseMessage res = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            ValidMessage rm = (ValidMessage) tgtools.util.JsonParseHelper.parseToObject(json, ValidMessage.class);

            mUserService.tokenLogin(request.getRemoteAddr(), rm.getUser(), rm.getToken());

            Object obj = restCommand.process(rm.getOperation(), rm.getData());
            res.setStatus(true);
            res.setData(obj);
        } catch (Exception e) {
            res.setStatus(false);
            res.setData(e.getMessage());
        }
        try {
            System.out.println("client结果：" + tgtools.util.JsonParseHelper.parseToJsonObject(res).toString());
        } catch (Exception d) {
        }
        return res;
    }
1181192
public SendMessageResult sendMessageSync(SendMessageRequest request) {
        Future<SendMessageResult> future = sendMessage(request, null);
        return waitForFuture(future);
    }
1117214
@Override
    public <T> T invoke(Context context, Class<T> classOfT) {
        return invoke(context, classOfT, null);
    }
855883
void doAwaitUntil() throws InterruptedException {
        lock.lock();
        try {
            condition.await(DEFAULT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
        } finally {
            lock.unlock();
        }
    }
1338731
static String formatTimeout(final CouchbaseRequest request, final long timeout) {
        Map<String, Object> fieldMap = new HashMap<String, Object>();
        fieldMap.put("t", timeout);

        if (request != null) {
            fieldMap.put("s", formatServiceType(request));
            putIfNotNull(fieldMap, "i", request.operationId());
            putIfNotNull(fieldMap, "b", request.bucket());
            putIfNotNull(fieldMap, "c", request.lastLocalId());
            putIfNotNull(fieldMap, "l", request.lastLocalSocket());
            putIfNotNull(fieldMap, "r", request.lastRemoteSocket());
        }

        try {
            return DefaultObjectMapper.writeValueAsString(fieldMap);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Could not format timeout information for request " + request, e);
            return null;
        }
    }
698486
private Object waitForResult(long timeoutMillis)
                    throws ExecutionException, InterruptedException, TimeoutException, RemoteException { // F16043
        final boolean isTraceOn = svLogger.isLoggable(Level.FINER);
        if (isTraceOn)
            svLogger.entering(CLASS_NAME, "waitForResult", Long.valueOf(timeoutMillis));

        long begin = System.nanoTime();
        // The nanoTime updated before every call to
        // RemoteAsyncResultExtended.waitForResult.
        long beginLastAttempt = begin;
        // The nanoTime when we should stop waiting altogether.  This value is
        // only used if timeout is non-zero.
        long end = begin + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);

        // True if the client ORB has ever thrown a NO_RESPONSE.
        boolean noResponse = false;
        // The waitTime argument for the next call to
        // RemoteAsyncResultExtended.waitForResult.
        long waitTimeMillis = timeoutMillis;
        // The maximum value for waitTimeMillis.  This value is lazily
        // initialized when a NO_RESPONSE occurs.
        long maxWaitTimeMillis = -1;

        for (;;) {
            if (isTraceOn)
                svLogger.entering(CLASS_NAME, "waitForResult", "waiting " + waitTimeMillis);

            Object[] resultArray;
            try {
                resultArray = stubWaitForResult((Stub) ivServer, waitTimeMillis);
            } catch (RemoteException ex) {
                Throwable cause = ex.getCause();

                // If this is the first NO_RESPONSE, then try again with a shorter
                // server-side wait time.  For subsequent NO_RESPONSE, assume there
                // is a connection issue and rethrow the exception.
                if (cause instanceof NO_RESPONSE && !noResponse) {
                    if (isTraceOn)
                        svLogger.logp(Level.FINER, CLASS_NAME, "waitForResult", "retrying", cause);
                    resultArray = null;
                    noResponse = true;
                } else {
                    if (isTraceOn)
                        svLogger.exiting(CLASS_NAME, "waitForResult", ex);
                    throw ex;
                }
            }

            if (resultArray != null) {
                if (isTraceOn)
                    svLogger.exiting(CLASS_NAME, "waitForResult", "result");
                return resultArray[0];
            }

            // Either the client ORB or the server timed us out.  Choose a lower
            // waitTimeMillis and then try again.

            long now = System.nanoTime();

            if (timeoutMillis > 0) {
                long remainingMillis = TimeUnit.NANOSECONDS.toMillis(end - now);
                if (remainingMillis <= 0) {
                    if (isTraceOn)
                        svLogger.exiting(CLASS_NAME, "waitForResult", "timeout");
                    throw new TimeoutException();
                }

                waitTimeMillis = remainingMillis;
            }

            if (noResponse) {
                if (maxWaitTimeMillis == -1) {
                    // For the first NO_RESPONSE, set maximum server wait time for
                    // all subsequent requests based on how long the ORB actually
                    // waited before timing out this request.  Back off a little bit
                    // to give time for the server to respond.
                    long actualWaitTimeMillis = TimeUnit.NANOSECONDS.toMillis(now - beginLastAttempt);
                    maxWaitTimeMillis = Math.max(MIN_ASYNC_RESULT_NO_RESPONSE_WAIT_TIME,
                                                 actualWaitTimeMillis - AsyncResultNoResponseBackoff);
                }

                if (timeoutMillis == 0) {
                    waitTimeMillis = maxWaitTimeMillis;
                } else {
                    waitTimeMillis = Math.min(waitTimeMillis, maxWaitTimeMillis);
                }
            }

            beginLastAttempt = now;
        }
    }
665353
public <T extends Response> T sendrecv ( Request request, T response, Set<RequestParam> params ) throws IOException {
        if ( isDisconnected() && this.state != 5 ) {
            throw new TransportException("Transport is disconnected " + this.name);
        }
        try {
            long timeout = !params.contains(RequestParam.NO_TIMEOUT) ? getResponseTimeout(request) : 0;

            long firstKey = doSend(request, response, params, timeout);

            if ( Thread.currentThread() == this.thread ) {
                // we are in the transport thread, ie. on idle disconnecting
                // this is synchronous operation
                // This does not handle compound requests
                synchronized ( this.inLock ) {
                    Long peekKey = peekKey();
                    if ( peekKey == firstKey ) {
                        doRecv(response);
                        response.received();
                        return response;
                    }
                    doSkip(peekKey);
                }
            }

            return waitForResponses(request, response, timeout);
        }
        catch ( IOException ioe ) {
            log.warn("sendrecv failed", ioe);
            try {
                disconnect(true);
            }
            catch ( IOException ioe2 ) {
                ioe.addSuppressed(ioe2);
                log.info("disconnect failed", ioe2);
            }
            throw ioe;
        }
        catch ( InterruptedException ie ) {
            throw new TransportException(ie);
        }
        finally {
            Response curResp = response;
            Request curReq = request;
            while ( curResp != null ) {
                this.response_map.remove(curResp.getMid());
                Request next = curReq.getNext();
                if ( next != null ) {
                    curReq = next;
                    curResp = next.getResponse();
                }
                else {
                    break;
                }
            }
        }
    }
1217323
public <T> T execute(WebDriverLikeRequest request) {
    Response response = null;
    long total = 0;
    try {
      HttpClient client = newHttpClientWithTimeout();
      String url = remoteURL + request.getPath();
      BasicHttpEntityEnclosingRequest
          r =
          new BasicHttpEntityEnclosingRequest(request.getMethod(), url);
      if (request.hasPayload()) {
        r.setEntity(new StringEntity(request.getPayload().toString(), "UTF-8"));
      }

      HttpHost h = new HttpHost(remoteURL.getHost(), remoteURL.getPort());
      long start = System.currentTimeMillis();
      HttpResponse res = client.execute(h, r);
      total = System.currentTimeMillis() - start;

      response = Helper.exctractResponse(res);
    } catch (Exception e) {
      throw new WebDriverException(e);
    }
    response = errorHandler.throwIfResponseFailed(response, total);
    try{
    return cast(response.getValue());
    }catch (ClassCastException e){
      log.warning(e.getMessage()+" for "+response.getValue());
      throw e;
    }
  }
1350637
@Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (this.m_coordinationLatch.await(timeout, unit) == false) {
            throw new TimeoutException();
        }

        if (m_pendingException != null) {
            if (m_pendingException instanceof ExecutionException) {
                throw (ExecutionException) m_pendingException;
            } else {
                throw (RuntimeException) m_pendingException;
            }
        }

        throw new CancellationException();
    }
579152
@Override
    public final T poll(final long timeout, final TimeUnit unit) throws InterruptedException {
        final long start = getWriteLockWithOptionalWait(timeout, unit);
        if (start == Long.MIN_VALUE) {
            // Min value signals a timeout while waiting
            return null;
        }
        final long maxWait = start >= 0 ? unit.toMillis(timeout) : -1;

        try {
            // Wait for an element to be available to return
            if (!this.waitForAdd(start, maxWait)) {
                return null;
            }

            return this.pollInternal(false);
        } finally {
            this.writeLock.unlock();
        }
    }
1200956
protected SofaResponse doInvokeSync(SofaRequest request, int timeout) throws InterruptedException,
        ExecutionException, TimeoutException {
        HttpResponseFuture future = new HttpResponseFuture(request, timeout);
        AbstractHttpClientHandler callback = new SyncInvokeClientHandler(transportConfig.getConsumerConfig(),
            transportConfig.getProviderInfo(), future, request, RpcInternalContext.getContext(),
            ClassLoaderUtils.getCurrentClassLoader());
        future.setSentTime();
        doSend(request, callback, timeout);
        future.setSentTime();
        return future.getSofaResponse(timeout, TimeUnit.MILLISECONDS);
    }
709538
protected <R> R executeRequest(Request request, JavaType javaType)
    {
        long start = System.currentTimeMillis();
        boolean error = true;
        try
        {
            Response response = executeRequest(request);
            R r = readResponse(response, javaType);
            error = false;
            return r;
        }
        finally
        {
            if(clientEventListener != null)
            {
                ClientEvent event = new ClientEvent(baseUrl,request.getEntityName(),request.getRequestMethod(),
                        System.currentTimeMillis() - start,error);
                clientEventListener.handleEvent(event);
            }
        }
    }
66182
public static void pickupFromRequest(RpcInvokeContext context, SofaRequest request, boolean init) {
        if (context == null && !init) {
            return;
        }
        // 解析请求 
        Map<String, String> requestBaggage = (Map<String, String>) request
            .getRequestProp(RemotingConstants.RPC_REQUEST_BAGGAGE);
        if (CommonUtils.isNotEmpty(requestBaggage)) {
            if (context == null) {
                context = RpcInvokeContext.getContext();
            }
            context.putAllRequestBaggage(requestBaggage);
        }
    }
510602
public static void serverFilter(ContainerRequestContext requestContext) {
        try {
            SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
            SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
            if (serverSpan != null) {
                RpcInternalContext context = RpcInternalContext.getContext();

                context.setAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME, RpcRuntimeContext.now());

                SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                        ((PostMatchContainerRequestContext) requestContext)
                            .getResourceMethod();

                SofaResourceFactory factory = resourceMethodInvoker.getResource();
                String serviceName = factory.getServiceName();
                String appName = factory.getAppName();

                if (serviceName == null) {
                    serviceName = resourceMethodInvoker.getResourceClass().getName();
                }
                serverSpan.setTag(RpcSpanTags.SERVICE, serviceName);
                if (resourceMethodInvoker.getMethod() != null) {
                    serverSpan.setTag(RpcSpanTags.METHOD, resourceMethodInvoker.getMethod().getName());
                    //serverSend需要
                    context.setAttachment(METHOD_TYPE_STRING, resourceMethodInvoker.getMethod());
                }

                serverSpan.setTag(RpcSpanTags.REMOTE_IP, context.getRemoteHostName()); // 客户端地址

                String remoteAppName = requestContext.getHeaderString(RemotingConstants.HEAD_APP_NAME);
                if (StringUtils.isNotBlank(remoteAppName)) {
                    serverSpan.setTag(RpcSpanTags.REMOTE_APP, remoteAppName);
                }
                serverSpan.setTag(RpcSpanTags.PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
                serverSpan.setTag(RpcSpanTags.INVOKE_TYPE, RpcConstants.INVOKER_TYPE_SYNC);
                if (appName == null) {
                    appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
                }
                serverSpan.setTag(RpcSpanTags.LOCAL_APP, appName);
            }
        } catch (Throwable t) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("the process of rest tracer server filter occur error ", t);
            }
        }
    }
288519
public void sendRequest(Message request, Object context, Message.Builder responseBuilder,
                          Duration timeout) {
    // Pack it as a no-timeout request and send it!
    final REQID rid = REQID.generate();
    contextMap.put(rid, context);
    responseMessageMap.put(rid, responseBuilder);

    // Add timeout for this request if necessary
    if (timeout.getSeconds() > 0) {
      registerTimerEvent(timeout, new Runnable() {
        @Override
        public void run() {
          handleTimeout(rid);
        }
      });
    }

    OutgoingPacket opk = new OutgoingPacket(rid, request);
    socketChannelHelper.sendPacket(opk);
  }
236403
public int sendRpcMessage(TLMethod request, long timeout, boolean highPriority) {
        int id = scheduller.postMessage(request, true, timeout, highPriority);
        Logger.d(TAG, "sendMessage #" + id + " " + request.toString() + " with timeout " + timeout + " ms");
        return id;
    }