Answer a new {@code Client} from the {@code configuration}.
@param configuration the Configuration
@param type the ClientConsumerType
@param poolSize the int size of the pool of workers
@return Client
@throws Exception when the Client cannot be created
772017
public static Client using(final Configuration configuration, final ClientConsumerType type, final int poolSize) throws Exception {
    return new Client(configuration, type, poolSize);
  }
48525
@Override
	protected AsyncTaskProcessorThread createPoolObject() throws Exception
	{
		AsyncTaskProcessorThread thread = new AsyncTaskProcessorThread(listener);
		thread.setName(name);
		thread.start();	
		return thread;
	}
836478
protected ConfiguredCloseableHttpClient createClient(
            final org.apache.http.impl.client.HttpClientBuilder builder,
            final InstrumentedHttpClientConnectionManager manager,
            final String name) {
        final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
        final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
        final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
        final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
        final long keepAlive = configuration.getKeepAlive().toMilliseconds();
        final ConnectionReuseStrategy reuseStrategy = keepAlive == 0
                ? new NoConnectionReuseStrategy()
                : new DefaultConnectionReuseStrategy();
        final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0
                ? NO_RETRIES
                : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(),
                false) : httpRequestRetryHandler);

        final RequestConfig requestConfig
                = RequestConfig.custom().setCookieSpec(cookiePolicy)
                .setSocketTimeout(timeout)
                .setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .build();
        final SocketConfig socketConfig = SocketConfig.custom()
                .setTcpNoDelay(true)
                .setSoTimeout(timeout)
                .build();

        customizeBuilder(builder)
                .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name))
                .setConnectionManager(manager)
                .setDefaultRequestConfig(requestConfig)
                .setDefaultSocketConfig(socketConfig)
                .setConnectionReuseStrategy(reuseStrategy)
                .setRetryHandler(retryHandler)
                .setUserAgent(createUserAgent(name));

        if (keepAlive != 0) {
            // either keep alive based on response header Keep-Alive,
            // or if the server can keep a persistent connection (-1), then override based on client's configuration
            builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    final long duration = super.getKeepAliveDuration(response, context);
                    return (duration == -1) ? keepAlive : duration;
                }
            });
        }

        // create a tunnel through a proxy host if it's specified in the config
        final ProxyConfiguration proxy = configuration.getProxyConfiguration();
        if (proxy != null) {
            final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
            builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
            // if the proxy host requires authentication then add the host credentials to the credentials provider
            final AuthConfiguration auth = proxy.getAuth();
            if (auth != null) {
                if (credentialsProvider == null) {
                    credentialsProvider = new BasicCredentialsProvider();
                }
                // set the AuthScope
                AuthScope authScope = new AuthScope(httpHost, auth.getRealm(), auth.getAuthScheme());

                // set the credentials type
                Credentials credentials = configureCredentials(auth);

                credentialsProvider.setCredentials(authScope, credentials);
            }
        }


        if (credentialsProvider != null) {
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        if (routePlanner != null) {
            builder.setRoutePlanner(routePlanner);
        }

        if (disableContentCompression) {
            builder.disableContentCompression();
        }

        if (redirectStrategy != null) {
            builder.setRedirectStrategy(redirectStrategy);
        }

        if (defaultHeaders != null) {
            builder.setDefaultHeaders(defaultHeaders);
        }

        if (verifier != null) {
            builder.setSSLHostnameVerifier(verifier);
        }

        if (httpProcessor != null) {
            builder.setHttpProcessor(httpProcessor);
        }

        if (serviceUnavailableRetryStrategy != null) {
            builder.setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy);
        }

        return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
    }
605032
public static ClientConfiguration createClient(final List<Endpoint> endpoints, final List<DataProvider> providers) {
        return createClient(null, null, endpoints, providers);
    }
726550
public static ClientConfiguration createClient(final Endpoint endpoint, final DataProvider provider) {
        return createClient(singletonList(endpoint), singletonList(provider));
    }
135545
@Override
    protected Client instantiateClient(String persistenceUnit)
    {
        ConnectionPool pool = getPoolUsingPolicy();
        return new ThriftClient(this, indexManager, reader, persistenceUnit, pool, externalProperties, kunderaMetadata, timestampGenerator);
    }
79809
private HttpClient createPooledClient() {
    HttpParams connMgrParams = new BasicHttpParams();
    
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme(HTTP_SCHEME, PlainSocketFactory.getSocketFactory(), HTTP_PORT));
    schemeRegistry.register(new Scheme(HTTPS_SCHEME, SSLSocketFactory.getSocketFactory(), HTTPS_PORT));
    
    // All connections will be to the same endpoint, so no need for per-route configuration.
    // TODO See how this does in the presence of redirects.
    ConnManagerParams.setMaxTotalConnections(connMgrParams, poolSize);
    ConnManagerParams.setMaxConnectionsPerRoute(connMgrParams, new ConnPerRouteBean(poolSize));
    
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(connMgrParams, schemeRegistry);
    
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    ConnManagerParams.setTimeout(httpParams, acquireTimeout * 1000);
    return new DefaultHttpClient(ccm, httpParams);
  }
655713
public static <T> T buildProxy(String proxyType, Class<T> clazz, Invoker proxyInvoker) throws Exception {
        try {
            ExtensionClass<Proxy> ext = ExtensionLoaderFactory.getExtensionLoader(Proxy.class)
                .getExtensionClass(proxyType);
            if (ext == null) {
                throw ExceptionUtils.buildRuntime("consumer.proxy", proxyType,
                    "Unsupported proxy of client!");
            }
            Proxy proxy = ext.getExtInstance();
            return proxy.getProxy(clazz, proxyInvoker);
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new SofaRpcRuntimeException(e.getMessage(), e);
        }
    }
235990
public static ClientBuilder cluster() throws IOException {
    final ClientBuilder builder = new ClientBuilder();

    final String host = System.getenv(ENV_SERVICE_HOST);
    final String port = System.getenv(ENV_SERVICE_PORT);
    builder.setBasePath("https://" + host + ":" + port);

    final String token =
        new String(
            Files.readAllBytes(Paths.get(SERVICEACCOUNT_TOKEN_PATH)), Charset.defaultCharset());
    builder.setCertificateAuthority(Files.readAllBytes(Paths.get(SERVICEACCOUNT_CA_PATH)));
    builder.setAuthentication(new AccessTokenAuthentication(token));

    return builder;
  }
997526
public static <T> MemcachedClientBuilder<T> newJsonClient(final ObjectMapper objectMapper, final Class<T> valueType) {
    return newClient(new JsonTranscoder<>(objectMapper, valueType));
  }
386501
public HttpClient createClient(int maxConnPerRoute, int connTimeoutMillis, int soTimeoutMillis, @Nullable String proxyHostAnPort) {
		Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder
			.<ConnectionSocketFactory> create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();
		PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry);
			connMgr.setDefaultMaxPerRoute(maxConnPerRoute);
		RequestConfig rCfg = RequestConfig.custom()
			.setConnectTimeout(connTimeoutMillis)
			.setSocketTimeout(soTimeoutMillis)
			.build();
		HttpClientBuilder hcb = HttpClientBuilder.create()
			.setConnectionManager(connMgr)
			.setDefaultRequestConfig(rCfg);
		if (proxyHostAnPort == null) {
			// do something?
		} else if("jvm".equalsIgnoreCase(proxyHostAnPort)) {
			SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
			hcb.setRoutePlanner(rp);
		} else {
			String[] hostAndPort = proxyHostAnPort.split(":");
			Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:"+proxyHostAnPort);
			String host = hostAndPort[0];
			int port = 80;
			if (hostAndPort.length > 1) {
				port = Integer.valueOf(hostAndPort[1]);
			}
			HttpHost proxy = new HttpHost(host, port);
			hcb.setProxy(proxy);
		}
		HttpClient httpClient = hcb.build();
		return httpClient;
	}
390166
public static ExecutorService createPool(PoolType type, String format) {
        //检查是否符合格式
        String.format(format, 0);
        //线程工厂
        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger counter = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format(format, counter.getAndAdd(1)));
            }
        };

        return build(type, factory);
    }
245341
public ClientConfiguration createClientConfiguration() {
        return ClientConfiguration.builder(buildTimeSeriesUrl(), username, password)
                .connectTimeoutMillis(connectTimeoutMillis)
                .readTimeoutMillis(readTimeoutMillis)
                .pingTimeoutMillis(pingTimeoutMillis)
                .ignoreSSLErrors(ignoreSSLErrors)
                .skipStreamingControl(skipStreamingControl)
                .enableBatchCompression(enableGzipCompression)
                .userAgent(userAgent)
                .build();
    }
238831
public synchronized ClientBuilder newBuilder(String clientName, JaxRsClientConfig jaxRsConfig, Collection<JaxRsFeatureGroup> featureGroupsIn) {
        started = true;

        final List<JaxRsFeatureGroup> featureGroups = ImmutableList.<JaxRsFeatureGroup>builder()
                .add(PrivateFeatureGroup.WILDCARD)
                .addAll(featureGroupsIn)
                .build();

        final ClientBuilder builder = factory(ctx).newBuilder(clientName, jaxRsConfig, featureGroups);

        builder.property(CLIENT_NAME_PROPERTY, clientName);
        builder.property(FEATURE_GROUP_PROPERTY, featureGroups);

        final List<Feature> features = featureGroups.stream()
            .flatMap(g -> featureMap.get(g).stream())
            .collect(Collectors.toList());

        final List<Class<? extends Feature>> classFeatures = featureGroups.stream()
            .flatMap(g -> classFeatureMap.get(g).stream())
            .collect(Collectors.toList());

        LOG.debug("Building client '{}' with feature groups {}, features {} {}, and config '{}'", clientName, featureGroups, features, classFeatures, jaxRsConfig);
        features.forEach(builder::register);
        classFeatures.forEach(builder::register);

        return builder;
    }
510705
protected ClientTransportConfig providerToClientConfig(ProviderInfo providerInfo) {
        return new ClientTransportConfig()
            .setConsumerConfig(consumerConfig)
            .setProviderInfo(providerInfo)
            .setContainer(consumerConfig.getProtocol())
            .setConnectTimeout(consumerConfig.getConnectTimeout())
            .setInvokeTimeout(consumerConfig.getTimeout())
            .setDisconnectTimeout(consumerConfig.getDisconnectTimeout())
            .setConnectionNum(consumerConfig.getConnectionNum())
            .setChannelListeners(consumerConfig.getOnConnect());
    }
845363
@Override
    public ORB createClientORB(Map<String, Object> clientProps, Collection<SubsystemFactory> subsystemFactories) throws ConfigException {
        return createORB(translateToClientArgs(clientProps, subsystemFactories), translateToClientProps(clientProps, subsystemFactories));
    }
56990
private IJdbcClient createClient(IPolicyContext context, JDBCIdentitySource config) throws Throwable {
        IJdbcComponent jdbcComponent = context.getComponent(IJdbcComponent.class);

        if (config.getType() == JDBCType.datasource || config.getType() == null) {
            DataSource ds = lookupDatasource(config);
            return jdbcComponent.create(ds);
        }
        if (config.getType() == JDBCType.url) {
            JdbcOptionsBean options = new JdbcOptionsBean();
            options.setJdbcUrl(config.getJdbcUrl());
            options.setUsername(config.getUsername());
            options.setPassword(config.getPassword());
            options.setAutoCommit(true);
            return jdbcComponent.createStandalone(options);
        }
        throw new Exception("Unknown JDBC options."); //$NON-NLS-1$
    }