springcloud openFeign 单机版使用。

说明:

1、所谓单机版,就是只是通过URL直接http调用,不依赖ribbon和hystrix,跟微服务不搭嘎。单纯学习下feign,未以后使用微服务做铺垫。
2、主要是学习openFeign自动配置怎么使用和自动配置原理。
3、分析一波配置自动配置httpclient源码

demo

1 依赖:



    org.springframework.cloud
    spring-cloud-dependencies
    Finchley.SR2
    pom
    import



    org.springframework.cloud
    spring-cloud-starter-openfeign
    2.0.2.RELEASE



    com.netflix.feign
    feign-httpclient
    8.18.0


2 application.yml 配置

##默认client设置,启用了httpclient配置,client配置超时会被替代
feign.client.config.default.logger-level=full
##feign httpclient配置,连接池配置。
feign.httpclient.enabled=true
feign.httpclient.max-connections=60
feign.httpclient.max-connections-per-route=30
feign.httpclient.connection-timeout=60000
# 配置请求GZIP压缩
feign.compression.request.enabled=true
# 配置响应GZIP压缩
feign.compression.response.enabled=true
#支持压缩的mime types
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048

3、代码

/**
* @EnableFeignClients 设置客户端扫描包
* @EnableFeignClients 会扫描所有@FiegnClient注解的接口。
**/
@SpringBootApplication
@EnableFeignClients(basePackages = "com.dayan.client")
public class SpringdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringdemoApplication.class, args);
    }

}

/**
* 客户端说明
*@FeignClient  feign客户端
*   1、url:单机版,用来指定调用服务url
*   2、name:2.0版本必填,单机版没啥用,微服务版本,用来指定注册中心的服务名称。
* springcloudopenfeign,支持了springmvc标签,对openfeign进行了扩展
**/
@FeignClient(url = "${sys.demoUrl}",name = "gitService")
public interface GithubClient {
    @RequestMapping(method = RequestMethod.GET, value = "/repos/{owner}/{repo}/contributors")
    List contributors(@PathVariable("owner") String owner, @PathVariable("repo") String repo);
}

##以上完事后,直接可以用@Autowire 调用了。

httpclient 自动配置遇到的坑。

官网中对于httpclient支持的介绍,只是and having them on the classpath一句话,没有具体指什么包依赖,这边坑我已经踩了。springcloud openfeign需要依赖feign-httpclient包,而不是httpclient-common就行原因如下:

    @Configuration
    //apachehttpclient 为 feign-httpclient包里面的类,重点这个包在下面的包中,根本没用,纯属让你用feign-httpclient包?
    @ConditionalOnClass(ApacheHttpClient.class)
    @ConditionalOnMissingClass("com.netflix.loadbalancer.ILoadBalancer")
    @ConditionalOnMissingBean(CloseableHttpClient.class)
    @ConditionalOnProperty(value = "feign.httpclient.enabled", matchIfMissing = true)
    protected static class HttpClientFeignConfiguration {
        private final Timer connectionManagerTimer = new Timer(
                "FeignApacheHttpClientConfiguration.connectionManagerTimer", true);

        @Autowired(required = false)
        private RegistryBuilder registryBuilder;

        private CloseableHttpClient httpClient;
        //创建httpclientConnectionManange
        @Bean
        @ConditionalOnMissingBean(HttpClientConnectionManager.class)
        public HttpClientConnectionManager connectionManager(
                ApacheHttpClientConnectionManagerFactory connectionManagerFactory,
                FeignHttpClientProperties httpClientProperties) {
            //通过ApacheHttpClientConnectionManagerFactory 创建,底层为PoolingHttpClientConnectionManager独享
            final HttpClientConnectionManager connectionManager = connectionManagerFactory
                    .newConnectionManager(httpClientProperties.isDisableSslValidation(), httpClientProperties.getMaxConnections(),//最大连接数
                            httpClientProperties.getMaxConnectionsPerRoute(),
                            httpClientProperties.getTimeToLive(),//存活时间
                            httpClientProperties.getTimeToLiveUnit(), registryBuilder);
            //启动个定时任务,每隔30秒清理失效的连接数。
            this.connectionManagerTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    connectionManager.closeExpiredConnections();
                }
            }, 30000, httpClientProperties.getConnectionTimerRepeat());
            return connectionManager;
        }

        //创建httpclient bean
        @Bean
        public CloseableHttpClient httpClient(ApacheHttpClientFactory httpClientFactory,
                HttpClientConnectionManager httpClientConnectionManager,
                FeignHttpClientProperties httpClientProperties) {
            //创建RequsetConfig 设置超时时间
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setConnectTimeout(httpClientProperties.getConnectionTimeout())
                    .setRedirectsEnabled(httpClientProperties.isFollowRedirects())
                    .build();
            //创建httpclient对象。
            this.httpClient = httpClientFactory.createBuilder().
                    setConnectionManager(httpClientConnectionManager).
                    setDefaultRequestConfig(defaultRequestConfig).build();
            return this.httpClient;
        }

关于feign,调用自身服务,重复调用问题。

调用代码
@FeignClient(url = "${tuna.url}",name = "tunaClient" ,configuration = TunaClientConfig.class)
@RequestMapping( consumes = MediaType.APPLICATION_JSON_VALUE)
public interface TunaClient {
    @RequestMapping(method = RequestMethod.POST, value = "/v1/out/category")
    TunaResult book( @RequestHeader(name="sign")String sign,//通用参数 sign
                            @RequestHeader(name="timeStamp")String timeStamp, //通用参数 timeStamp
                            @RequestHeader(name="appId")String appId, //通用参数 timeStamp,
                            @RequestBody BookParam bookParam);
}
接口代码:
@Api(tags = "第三方接口管理")
@RequestMapping(value="/v1/out",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public interface ThirdPartyFacade {
    @ApiOperation("查询规格")
    @RequestMapping(value = "category", method = RequestMethod.POST)
    @ResponseBody
    ResultMessage category();

如下图所示为判断是否为handler的条件(@Controller 或者@RequsetMapping 注释的类)
1、springmvc 会将@Contoller 或者@RequsetMapping注册到dispatchservlet中。
2、由于feign调用时,requsetMapping注释到接口层(本意设置通用配置),所以被作为handler,注册到了dispatchservlet中。
3、当自己调用自己时,因为feign调用服务申明的路径和接口路径是一致的,而feign的申明也注册到了dispatchservlet中,所以出现了feign调用了自己然后无限调用的情况。、
4、解决办法是,不用在申明feign时,再接口上定义@requsetmapping

    @Override
    protected boolean isHandler(Class beanType) {
        return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
                AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
    }


你可能感兴趣的:(springcloud openFeign 单机版使用。)