[SpringCloud-4] Feign call

In the previous study, it is troublesome to call another service by using RestTemplate and encapsulating the url by yourself. It is relatively simple to use feign, and it can be done with one annotation. It is actually a lightweight http service client, and, it also has load balancing and circuit breaker capabilities: Feign = RestTemplate+Ribbon+Hystrix

The basic use of feign:

1. Import dependencies into consumer services

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

2. The startup class uses the annotation @EnableFeignClients

Note: At this time, remove the support annotation @EnableCircuitBreaker for Hystrix circuit breaker to include the imported dependencies, because Feign will automatically import them

3. Create feign interface

// @FeignClient表明当前类是一个Feign客户端,value指定该客户端要请求的服务名称(登记到注册中心上的服务提供者的服务名称)
@FeignClient(value = "lagou-service-resume")
@RequestMapping("/resume")
public interface ResumeServiceFeignClient {


    // Feign要做的事情就是,拼装url发起请求
    // 我们调用该方法就是调用本地接口方法,那么实际上做的是远程请求
    @GetMapping("/openstate/{userId}")
    public Integer findDefaultResumeState(@PathVariable("userId") Long userId);

}

As above, the url is specified in the way of springmvc, which is very convenient. Specify the service and interface to call, and then use @Autowire injection when using it. 

feign's support for load balancing: 

Feign itself has integrated Ribbon dependencies and automatic configuration, so we don't need to introduce additional dependencies, and we can configure them through ribbon.xx (that is, the ribbon configuration method we learned before). In addition, when feign calls, you can specify the interface timeout (default 1s), but if you use the ribbon configuration, the ribbon will prevail.

 

Feign's support for fuses: 

For the support of fusing hystrix, there is no need to introduce dependencies separately, just need to enable the support in the configuration file:

# 开启Feign的熔断功能
feign:
  hystrix:
    enabled: true

Others can be used in the same way as before hystrix. It is worth noting that feign itself has a timeout setting. If the hystrix fuse timeout is set at this time, the smaller time will prevail, and the fuse mechanism will be entered after the time is exceeded. As I said before, the downgrade method can be specified after the fuse is broken, and the feign interface can also be specified here:

1. Define the fallback processing class:

/**
 * 降级回退逻辑需要定义一个类,实现FeignClient接口,实现接口中的方法
 *
 *
 */
@Component  // 别忘了这个注解,还应该被扫描到
public class ResumeFallback implements ResumeServiceFeignClient {
    @Override
    public Integer findDefaultResumeState(Long userId) {
        return -6;
    }
}

Directly implement the feign interface and rewrite all the logic of the original method.

2. Specify in the feign interface

@FeignClient(value = "lagou-service-resume",fallback = ResumeFallback.class,path = "/resume")
//@RequestMapping("/resume")
public interface ResumeServiceFeignClient {


    // Feign要做的事情就是,拼装url发起请求
    // 我们调用该方法就是调用本地接口方法,那么实际上做的是远程请求
    @GetMapping("/openstate/{userId}")
    public Integer findDefaultResumeState(@PathVariable("userId") Long userId);

}

As above, just specify the fallback attribute in the FeignClient annotation. It is worth noting that after using fallback, @RequestMapping("/resume") should be commented out, and the prefix /resume should be put in the path attribute of FeignClient, otherwise an error may be reported.

Feign's support for compression: 

When feign is called, there may be situations where the request or response body is too large. Feign can support compression, and you can directly configure the value to open it:

feign:
  compression:
    request:
      enabled: true # 开启请求压缩
      mime-types: text/html,application/xml,application/json # 设置压缩的数据类型,此处也是默认值
      min-request-size: 2048 # 设置触发压缩的⼤⼩下限,此处也是默认值
    response:
      enabled: true # 开启响应压缩

Feign's log level:  

Feign is an http request client, similar to our browser, it can print some more detailed log information (response header, status code, etc.) when requesting and receiving responses. If we want to see the log when Feign requests, we can configure it. By default, Feign 's log is not enabled.

// Feign的⽇志级别(Feign请求过程信息)
// NONE:默认的,不显示任何⽇志----性能最好
// BASIC:仅记录请求⽅法、URL、响应状态码以及执⾏时间----⽣产问题追踪
// HEADERS:在BASIC级别的基础上,记录请求和响应的header
// FULL:记录请求和响应的header、body和元数据----适⽤于开发及测试环境定位问题
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLevel() {
        return Logger.Level.FULL;
     }
}

You can also modify the log level for a feign interface:

logging:
   level:
# Feign⽇志只会对⽇志级别为debug的做出响应
 com.lagou.edu.controller.service.ResumeServiceFeignClient:debug

Guess you like

Origin blog.csdn.net/growing_duck/article/details/131213579