springcloud 实现微服务间调用

Posted 不负前行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud 实现微服务间调用相关的知识,希望对你有一定的参考价值。

package com.idoipo.ibt.config;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * Created by Jemmy on 2016/12/1.
 */
@Configuration
@SuppressWarnings("unused")
public class WebConfiguration {

    private Logger logger= LoggerFactory.getLogger(WebConfiguration.class);

    @Value("${com.idoipo.httpcomponent.maxconnperroute}")
    private int maxConnPerRoute;
    @Value("${com.idoipo.httpcomponent.maxconntotal}")
    private int maxConnTotal;
    @Value("${http.agent}")
    private String userAgent;


    //参考微信OA,使用HttpCommponent
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate=new RestTemplate(factory);
        restTemplate.setErrorHandler(new RestClientResponseErrorHandler());
        return restTemplate;
    }


    @Bean
    public HttpClient httpClient(){

        HttpClientBuilder builder= HttpClients.custom();

        PoolingHttpClientConnectionManager connectionManager=new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build());
        builder.setConnectionManager(connectionManager);
        builder.useSystemProperties();

        builder.setRetryHandler(new DefaultHttpRequestRetryHandler(5,false));

        //请求配置
        RequestConfig.Builder requestConfigBuilder=RequestConfig.copy(RequestConfig.DEFAULT);
        requestConfigBuilder.setConnectTimeout(1000*120);
        requestConfigBuilder.setConnectionRequestTimeout(1000*120);
        requestConfigBuilder.setSocketTimeout(1000*150);
        builder.setUserAgent(userAgent);

        builder.setDefaultRequestConfig(requestConfigBuilder.build());

        builder.setMaxConnPerRoute(maxConnPerRoute);
        builder.setMaxConnTotal(maxConnTotal);
        builder.addInterceptorLast(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                request.removeHeaders(HTTP.CONN_DIRECTIVE);
            }
        });

        //禁用cookie及认证缓存
        builder.disableAuthCaching();
        builder.disableCookieManagement();

        //打印client配置
        logger.debug("Http Client Configuration:{}",requestConfigBuilder.build().toString());
        return builder.build();
    }


    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(15000);//ms
        return factory;
    }

    class RestClientResponseErrorHandler extends DefaultResponseErrorHandler{

        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            throw new IOException("第三方服务调用时,发生错误");
        }

        @Override
        protected boolean hasError(HttpStatus statusCode) {
            return statusCode.series() == HttpStatus.Series.SERVER_ERROR;
        }
    }
}

 

以上是关于springcloud 实现微服务间调用的主要内容,如果未能解决你的问题,请参考以下文章

springcloudalibaba架构(31):SpringCloud实现用户信息在微服务之间传递(Feign和Dubbo)

SpringCloud学习系列-Hystrix断路器

服务间调用--feign跟ribbon

springcloud项目多个微服务中,jwt鉴权的代码应该放在哪个服务中?

深入讲解SpringCloud Alibaba 微服务调用,还不懂微服务的一定得看看!

Istio 微服务架构实现服务间gRPC通信