OpenFeign 学习笔记

目录

定义、使用

超时控制

重试配置

 配置请求压缩

日志打印功能

修改默认httpClien(修改为httpclient5)

参考:


定义、使用

是一个声明式的web服务客户端;只需要创建一个Rest接口并在该接口上添加注解@FeignClient即可

1、添加依赖 


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

 2、在 Spring Boot 应用程序的主类上添加 @EnableFeignClients 注解,以启用 OpenFeign

3、定义 Feign 接口

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List getStores();

    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    Page getStores(Pageable pageable);

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);

    @RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
    void delete(@PathVariable Long storeId);
}

超时控制

默认超时时间1分钟

spring:
  cloud:
    openfeign:
      client:
        config:
          default:
            #连接超时时间
            connectTimeout: 3000
            #读取超时时间
            readTimeout: 3000

或者 

feign:
  client:
    config:
      ## default 设置的全局超时时间,指定服务名称可以设置单个服务的超时时间
      default:
        connectTimeout: 5000
        readTimeout: 5000
      ## 为serviceC这个服务单独配置超时时间
      serviceC:
        connectTimeout: 30000
        readTimeout: 30000

重试配置

默认不重试
配置注入Retryer bean 

@Configuration
public class FeignConfig {
    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(100, SECONDS.toMillis(1), 5); // 这里配置重试间隔和重试次数
    }
}

 配置请求压缩

可以通过配置属性来启用请求和响应的GZIP压缩。以下是如何配置OpenFeign客户端以使用GZIP压缩的步骤

spring:
  cloud:
    openfeign:
      compression:
        request:
          enabled: true
          mime-types: text/xml,application/xml,application/json
          min-request-size: 2048
        response:
          enabled: true

或者

# application.yml
feign:
  compression:
    request:
      enabled: true
      mime-types: text/xml,application/xml,application/json
      min-request-size: 2048
    response:
      enabled: true

日志打印功能

1、配置日志Bean:

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

2、YML文件里需要开启日志的Feign客户端

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.gzl.cn.service.PaymentFeignService: debug

修改默认httpClien(修改为httpclient5)

添加httpclient5的依赖



    org.apache.httpcomponents.client5
    httpclient5
    5.3



    io.github.openfeign
    feign-hc5
    13.1

修改yaml配置文件

#  Apache HttpClient5 配置开启
spring:
  cloud:
    openfeign:
      httpclient:
        hc5:
          enabled: true

参考:

OpenFeign官方文档

你可能感兴趣的:(#,springcloud,学习,笔记)