@FeignClient 的使用

转自:关于FeignClient的使用大全——使用篇 - 简书

Fegin这个组件内部是 RestTemplate+Ribbon+Hystrix组成的

@FeignClient标签的常用属性如下:

  • name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
  • url: url一般用于调试,可以手动指定@FeignClient调用的地址
  • decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
  • configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
  • fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
  • fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
  • path: 定义当前FeignClient的统一前缀

一个最简单的使用FeignClient的例子如下:
1,添加maven依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-core</artifactId>
    <version>9.7.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-slf4j</artifactId>
    <version>9.7.0</version>
</dependency>

2,在main主入口类添加FeignClients启用注解

@EnableFeignClients
......

3,编写FeignClient代码

@FeignClient(name = "myFeignClient", url = "http://127.0.0.1:8001")
public interface MyFeignClient {
    @RequestMapping(method = RequestMethod.GET, value = "/participate")
    String getCategorys(@RequestParam Map<String, Object> params);
}

4,直接使用FeignClient

@Autowired
MyFeignClient myFeignClient;

到此,FeignClient便可正常使用一般的Http接口了~
5,如果想使用文件上传接口或者post的x-www-form-urlencoded接口,那需要做如下配置
添加依赖包

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

添加bean注解配置

@Bean
@Primary
@Scope("prototype")
public Encoder multipartFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
    return new SpringFormEncoder(new SpringEncoder(messageConverters));
}

定义文件上传接口

@RequestMapping(value = {"/demo/v1/upload"}, 
    method = {RequestMethod.POST}, 
    consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
ReturnResult<ImageVO> uploadFile(
    @RequestPart(value = "file") MultipartFile file, 
    @RequestParam(value = "bucketName", required = false) String bucketName);

6,如果想使用Apache的httpclient的连接池,可以做如下配置
添加依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>9.7.0</version>
</dependency>

添加属性配置

feign:
  okhttp: 
    enabled: false
  httpclient:
    enabled: true
    maxConnections: 20480
    maxConnectionsPerRoute: 512
    timeToLive: 60
    connectionTimeout: 10000
    userAgent: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0'

引入FeignAutoConfiguration配置

@Import(FeignAutoConfiguration.class)
@Configuration
public class FeignConfig {
    ...
}

经过这几步操作后,便可启用Apache的httpclient替换其内嵌httpclient。
7,如果想启用hystrix熔断降级,则可作如下配置
添加依赖

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-hystrix</artifactId>
    <version>9.7.0</version>
</dependency>

添加属性配置

feign:
  hystrix: 
    enabled: true

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 15000
  threadpool:
    default:
      coreSize: 40
      maximumSize: 100
      maxQueueSize: 100

添加降级策略

public class MyFeignClientFallback implements MyFeignClient {
    @Override
    public ReturnResult<ImageVO> uploadFile(MultipartFile file, String bucketName) {
        return new ReturnResult<>(5001);
    }
}

添加bean配置

@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
    return HystrixFeign.builder();
}

@Bean
public MyFeignClientFallback fb() {
    return new MyFeignClientFallback();
}

更新@FeignClient代码

@FeignClient(
    name = "myFeignClient", 
    url = "http://127.0.0.1:8001",
    fallback = MyFeignClientFallback.class,
    configuration = {FeignConfig.class})

8,如果想处理熔断的具体原因,可以做如下更新
更新熔断策略代码实现FallbackFactory接口

public class MyFeignClientFallback implements FallbackFactory<MyFeignClient> {
    @Override
    public MyFeignClient create(final Throwable cause) {
        return new MyFeignClient() {
            @Override
            public ReturnResult<ImageVO> uploadFile(MultipartFile file, String bucketName) {
                // 处理cause
                
                return new ReturnResult<>(5001);
            }
        };
    }
}

更新bean配置

@Bean
public MyFeignClientFallback fbf() {
    return new MyFeignClientFallback();
}

更新@FeignClient代码

@FeignClient(
    name = "myFeignClient", 
    url = "http://127.0.0.1:8001",
    fallbackFactory = MyFeignClientFallback.class,
    configuration = {FeignConfig.class})

9,如果想对请求与响应进行压缩,来减少网络通信的性能开销

我们可以通过配置就可以开启对请求与响应的压缩功能,需要我们在配置文件application.yml中添加如下配置

feign:
  compression:
    request:
    	# 开启请求压缩功能
      enabled: true  
      #设置压缩的数据类型,此处也是默认值
      mime-types: text/html,application/xml,application/json
      # 设置什么时候触发压缩,当大小超过2048的时候 
      min-request-size: 2048
      # 开启响应压缩功能
    response: 
      enabled: true
      useGzipDecoder: true

定义DefaultGzipDecoder的bean

    @Bean
    @Primary
    @ConditionalOnProperty("feign.compression.response.useGzipDecoder")
    public Decoder responseGzipDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new OptionalDecoder(new ResponseEntityDecoder(
                new DefaultGzipDecoder(new SpringDecoder(messageConverters))));
    }

10,通过配置开启Fegin的日志功能

要看到Fegin的日志信息需要2处配置,分别是Fegin自身日志 与 系统log的一个配置,开启Fegin日志功能

10.1,开启Fegin自身日志需要我们使用配置类来配置

@Configuration
public class FeginLogConfiguration {
    @Bean
    public Logger.Level  feginLogLevel(){
        return Logger.Level.FULL;
    }
}

Fegin log level 都有哪些

Logger.Level解释
NONE    表示不显示任何日志,默认
BASIC    基本的日志,能够记录请求方法、URL、响应状态码以及执行时间 适用于生产
HEADERS    在BASIC级别的基础上记录请求和响应的header
FULL    全部日志,记录请求和响应的header、body和元数据 适用于开发

10.2,log日志配置

需要我们在配置文件application.yml中配置log日志

#Feign日志只会对日志级别为debug的做出响应
logging:
  level:
    com.xuzhaocai.consumer.service.OrderStatisticFeginClient: debug

11,FeignClient的request的重试机制

定义重试bean

    @Bean
    @Primary
    public Retryer feignRetryer() {
        return Retryer.NEVER_RETRY;
    }

初始化Feign.builder

    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder(Retryer retryer) {
        return Feign.builder().retryer(retryer);
    }

12,动态请求地址的host

有时候,我们可能会需要动态更改请求地址的host,也就是@FeignClient中的url的值在我调用的是才确定。此时我们就可以利用他的一个高级用法实现这个功能:
在定义的接口的方法中,添加一个URI类型的参数即可,该值就是新的host。此时@FeignClient中的url值在该方法中将不再生效。如下:

@FeignClient(name = "categoryFeignClient",
             url = "http://127.0.0.1:10002", 
             fallback = CategoryFeignClientFallback.class,
             configuration = {FeignConfig.class})
public interface CategoryFeignClient {
    /**
     * 第三方业务接口
     * @param categoryIds 参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.GET, value = "/v1/categorys/multi")
    String getCategorys(@RequestParam("categoryIds") String categoryIds, URI newHost);
}

-End-

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的使用 `@FeignClient` 的示例: 假设你有一个名为 `UserService` 的微服务,它提供了一个 `/users/{id}` 的 RESTful API,返回指定用户 ID 的用户信息。现在你想在另一个微服务中调用这个 API,可以使用 `@FeignClient`。 首先,在你的 Maven 或 Gradle 项目中添加以下依赖: ```xml <!-- Maven --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.5.RELEASE</version> </dependency> ``` ```groovy // Gradle implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:2.2.5.RELEASE' ``` 然后,创建一个接口,使用 `@FeignClient` 注解指定要调用的微服务名称和 URL: ```java @FeignClient(name = "user-service", url = "${user-service.url}") public interface UserServiceClient { @GetMapping("/users/{id}") User getUserById(@PathVariable("id") Long id); } ``` 在这里,我们使用Spring 的占位符 `${user-service.url}`,它会从配置文件中读取 `user-service.url` 的值,以便动态设置要调用的 URL。 最后,在你的 Spring Boot 应用程序中使用 `@Autowired` 自动装配 `UserServiceClient` 并调用它的方法即可。 ```java @RestController public class MyController { @Autowired private UserServiceClient userServiceClient; @GetMapping("/users/{id}") public User getUserById(@PathVariable("id") Long id) { return userServiceClient.getUserById(id); } } ``` 这样,当你访问 `/users/{id}` 时,就会调用 `UserService` 微服务的 `/users/{id}` API 并返回用户信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值