异步调用

@param request       请求对象
@param rpcContext    RPC内置上下文
@param timeoutMillis 超时时间（毫秒）
559186
protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext, int timeoutMillis) {
        SofaResponseCallback listener = request.getSofaResponseCallback();
        if (listener != null) {
            AbstractHttpClientHandler callback = new CallbackInvokeClientHandler(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), listener, request, rpcContext,
                ClassLoaderUtils.getCurrentClassLoader());
            doSend(request, callback, timeoutMillis);
            return null;
        } else {
            HttpResponseFuture future = new HttpResponseFuture(request, timeoutMillis);
            AbstractHttpClientHandler callback = new FutureInvokeClientHandler(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), future, request, rpcContext,
                ClassLoaderUtils.getCurrentClassLoader());
            doSend(request, callback, timeoutMillis);
            future.setSentTime();
            return future;
        }
    }
1336009
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit) {
        return requestTimeout(delay, unit, null, null);
    }
510310
protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext,
                                           InvokeContext invokeContext, int timeoutMillis)
        throws RemotingException, InterruptedException {
        SofaResponseCallback listener = request.getSofaResponseCallback();
        if (listener != null) {
            // callback调用
            InvokeCallback callback = new BoltInvokerCallback(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), listener, request, rpcContext,
                ClassLoaderUtils.getCurrentClassLoader());
            // 发起调用
            RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis);
            return null;
        } else {
            // future 转为 callback
            BoltResponseFuture future = new BoltResponseFuture(request, timeoutMillis);
            InvokeCallback callback = new BoltFutureInvokeCallback(transportConfig.getConsumerConfig(),
                transportConfig.getProviderInfo(), future, request, rpcContext,
                ClassLoaderUtils.getCurrentClassLoader());
            // 发起调用
            RPC_CLIENT.invokeWithCallback(url, request, invokeContext, callback, timeoutMillis);
            future.setSentTime();
            return future;
        }
    }
436724
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name, @Nullable final Object data) {
        return timeoutManager.requestTimeout(context(), state().getSagaId(), delay, unit, name, data);
    }
705830
public long countQuery(SearchRequestBuilder countRequestBuilder,
            long timeoutMillis) {
        countRequestBuilder.setSize(0);
        return searchQuery("countQuery", countRequestBuilder, timeoutMillis)
                .getHits().getTotalHits();
    }
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);
        }
    }
973227
@Override
    public String invoke(Object connection, String request, int timeout, Map<String,String> metainfo)
    throws ConnectionException, AdapterException {
        String response;
        try{
            if (timeout<=0) timeout = DEFAULT_TIMEOUT;
            SoccomClient client = (SoccomClient)connection;
            client.putreq(request);
            response = client.getresp(timeout);
        } catch (SoccomException ex){
            if (ex.getErrorCode()==SoccomException.POLL_TIMEOUT)
                throw new ConnectionException(ConnectionException.CONNECTION_DOWN, ex.getMessage(), ex);
            else throw new AdapterException(-1, ex.getMessage(), ex);
        }
        return response;
    }
305594
public void setConnectTimeout(int millis) {
		ClientHttpRequestFactory f = getRequestFactory();
		if (f instanceof SimpleClientHttpRequestFactory) {
			((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
		else {
			((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
	}
874187
private void setConnectTimeout(HttpURLConnection connection) {
        try {
            Map<String, String> endpointProperties = this.api.getEndpointProperties();
            if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$
                int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$
                connection.setConnectTimeout(connectTimeoutMs);
            }
        } catch (Throwable t) {
        }
    }
925465
function timeout(req, delay) {
  setTimeout(_timeout, delay);

  function _timeout() {
    let callback = callbacks[req.id];

    if (!callback) return;

    let err = new Error("request timeout");

    err.name = "Timeout";

    callback(rpc.error(req, err).error);

    delete callbacks[req.id];
  }
}
709764
public <R extends Request<T>, T> R add(R request) {
        //Listener factories should be first so client can listen to events
        for (ListenerFactory listenerFactory : listenerFactories) {
            RequestListener.ResponseListener qResponseListener = listenerFactory
                    .getResponseListener(request);
            RequestListener.ErrorListener qErrorListener = listenerFactory.getErrorListener
                    (request);
            RequestListener.MarkerListener qMarkerListener = listenerFactory.getMarkerListener
                    (request);

            if (qMarkerListener != null) {
                request.addMarkerListener(qMarkerListener);
            }
            if (qResponseListener != null) {
                request.addResponseListener(qResponseListener);
            }
            if (qErrorListener != null) {
                request.addErrorListener(qErrorListener);
            }
        }
        if (JusLog.ErrorLog.isOn()) {
            request.addErrorListener(JusLog.ErrorLog.getLogger(request));
        }

        if (JusLog.ResponseLog.isOn()) {
            request.addResponseListener(JusLog.ResponseLog.getLogger(request));
        }

        if (JusLog.MarkerLog.isOn()) {
            request.addMarkerListener(JusLog.MarkerLog.getLogger(request));
        }
        request.addMarker(Request.EVENT_PRE_ADD_TO_QUEUE);
        Authenticator serverAuthenticator = null;
        Authenticator proxyAuthenticator = null;
        for (Authenticator.Factory factory : authenticatorFactories) {

            if (serverAuthenticator == null) {
                serverAuthenticator = factory.forServer(request.getUrl(), request
                        .getNetworkRequest());
                if (serverAuthenticator != null)
                    request.setServerAuthenticator(serverAuthenticator);
            }

            if (proxyAuthenticator == null) {
                proxyAuthenticator = factory.forProxy(request.getUrl(), request.getNetworkRequest
                        ());
                if (proxyAuthenticator != null)
                    request.setProxyAuthenticator(proxyAuthenticator);
            }

            if (proxyAuthenticator != null && serverAuthenticator != null) {
                break;
            }

        }

        for (Transformer.RequestTransformer transformer : requestTransformers) {
            if (transformer.filter == null || transformer.filter.apply(request)) {
                request.setNetworkRequest(transformer.transform(request.getNetworkRequest()));
            }
        }

        if (retryPolicyFactory != null) {
            request.setRetryPolicy(retryPolicyFactory.get(request));
        }
        if (redirectPolicyFactory != null) {
            request.setRedirectPolicy(redirectPolicyFactory.get(request));
        }

        if (connectivityManagerFactory != null) {
            request.setConnectivityManager(connectivityManagerFactory.get(request));
        }
        if (noConnectionPolicyFactory != null) {
            request.setNoConnectionPolicy(noConnectionPolicyFactory.get(request));
        }

        synchronized (currentRequests) {
            //check if not already cancelled
            if (request.isCanceled()) {
                request.finish(Request.EVENT_ADD_DISCARD_CANCELED);
            }
            // Process requests in the order they are added.
            request.setSequence(getSequenceNumber());
            // Tag the request as belonging to this queue and add it to the set of current requests.
            request.setRequestQueue(this);
            currentRequests.add(request);
        }
        request.addMarker(Request.EVENT_ADD_TO_QUEUE);

        // If the request is uncacheable, skip the cache queue and go straight to the network.
        if (!request.shouldCache()) {
            networkQueue.add(request);
            return request;
        }

        // Insert request into stage if there's already a request with the same cache key in flight.
        synchronized (waitingRequests) {
            String cacheKey = request.getCacheKey();
            if (waitingRequests.containsKey(cacheKey)) {
                // There is already a request in flight. Queue up.
                Queue<Request<?>> stagedRequests = waitingRequests.get(cacheKey);
                if (stagedRequests == null) {
                    stagedRequests = new LinkedList<>();
                }
                stagedRequests.add(request);
                waitingRequests.put(cacheKey, stagedRequests);
//                if (JusLog.DEBUG) {
//                    JusLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
//                }
                //todo add queue markers
            } else {
                // Insert 'empty list' queue for this cacheKey, indicating there is now a request in
                // flight.
                waitingRequests.put(cacheKey, new LinkedList<Request<?>>());
                cacheQueue.add(request);
            }
            return request;
        }
    }
5578
protected SofaResponse doInvokeSync(SofaRequest request, InvokeContext invokeContext, int timeoutMillis)
        throws RemotingException, InterruptedException {
        return (SofaResponse) RPC_CLIENT.invokeSync(url, request, invokeContext, timeoutMillis);
    }
1225330
protected void setTimeoutTime(int time) {
        int timeout = time;
        if (timeout == TCPRequestContext.NO_TIMEOUT) {
            this.timeoutTime = TCPRequestContext.NO_TIMEOUT;
            this.timeoutInterval = 0;
        } else {
            if (timeout == TCPRequestContext.USE_CHANNEL_TIMEOUT) {
                timeout = getConfig().getInactivityTimeout();
            }
            if (timeout != ValidateUtils.INACTIVITY_TIMEOUT_NO_TIMEOUT) {
                this.timeoutTime = System.currentTimeMillis() + timeout;
                this.timeoutInterval = timeout;
            } else {
                this.timeoutTime = TCPRequestContext.NO_TIMEOUT;
                this.timeoutInterval = 0;
            }
        }
    }
346269
private RequestConfig setTimeout(Context context) {
        int socketTimeout = 0;
        int connectionTimeout = 0;
        if ( context.getCustomerRequestTimeout() != null) {
            socketTimeout = context.getCustomerRequestTimeout();
        }else {
            String reqTimeout = Config.getProperty(Config.TIMEOUT_REQUEST);
            if (StringUtils.hasText(reqTimeout)) {
                socketTimeout = new Integer(reqTimeout.trim());
            }
        }

        String connTimeout = Config.getProperty(Config.TIMEOUT_CONNECTION);
        if (StringUtils.hasText(connTimeout)) {
            connectionTimeout = new Integer(connTimeout.trim());
        }
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionTimeout)
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .build();
        return defaultRequestConfig;

    }
1361603
private void setTimeout(HttpURLConnection httpUrlConnection) {
		String connTimeout = Config.getProperty(Config.TIMEOUT_CONNECTION);
		if (StringUtils.hasText(connTimeout)) {
			httpUrlConnection.setReadTimeout(new Integer(connTimeout.trim()));			
		}
		String reqTimeout = Config.getProperty(Config.TIMEOUT_REQUEST);
		if (StringUtils.hasText(reqTimeout)) {
			httpUrlConnection.setConnectTimeout(new Integer(reqTimeout.trim()));			
		}
	}
951238
public ClientFactoryBuilder connectTimeoutMillis(long connectTimeoutMillis) {
        checkArgument(connectTimeoutMillis > 0,
                      "connectTimeoutMillis: %s (expected: > 0)", connectTimeoutMillis);
        return channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                             ConvertUtils.safeLongToInt(connectTimeoutMillis));
    }
726120
def _timeoutRequest(self, msgId):
        
        d, _ = self._requests.pop(msgId, (None, None))
        if not d.called:
            d.errback(ZmqRequestTimeoutError(msgId))