Summary of Feign's entry and use

1 Introduction

Feign is a declarative HTTP client open sourced by Netflix and has been donated to the OpenFeign community.

The Spring Cloud OpenFeign component integrates Feign into the Spring Cloud system to implement declarative HTTP invocation of services. Compared with using RestTemplate to implement service calls, Feign simplifies code writing, improves code readability, and greatly improves development efficiency.

In addition to supporting Feign's own annotations, Spring Cloud OpenFeign additionally provides support for JAX-RS annotations and SpringMVC annotations. In particular, the support for SpringMVC annotations is a miracle, so that we don't need to learn Feign's own annotations, but directly use the super-familiar SpringMVC annotations.

At the same time, Spring Cloud OpenFeign further integrates Feign and Ribbon to provide load balancing functions. In addition, Feign itself has been integrated with Hystrix to provide service fault tolerance.

In this way, based on annotations, we can implement service calls extremely simply, and have the functions of load balancing and service fault tolerance.

2. Introductory case

Based on the previous article Riibon Getting Started Summary Modify the consumer based on the use case

dependency import

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

New Feign interface

/**
 * service provider feign
 *
 * @author xiao7
 */
@FeignClient(value = "cloud-provider")
public interface ProviderFeignService {

    /**
     * provider test interface
     *
     * @param name
     * @return
     */
    @GetMapping("/provider/index/{name}")
    String testProvider(@PathVariable("name") String name);
}

Configure startup class

@EnableFeignClients: When Feign is enabled, it will scan the Bean s required for the package registration of the startup class

/**
 * @author xiao7
 */
@EnableDiscoveryClient
@SpringBootApplication
@RibbonClient(value = "cloud-provider", configuration = FiveTimeRule.class)
@EnableFeignClients
public class ConsumerApplication8082 {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication8082.class, args);
    }
}

3. Customize Feign configuration

To implement Feign custom configuration, you can use configuration files and Spring JavaConfig in two ways.

3.1. Log configuration

In Feign, four log levels are defined:

  • NONE: do not print logs
  • BASIC: Only print basic information, including request method, request address, response status code, and request duration
  • HEADERS: On the basis of BASIC basic information, add request headers and response headers
  • FULL: Print the complete information, including all information of the request and response.

Configuration file method:

logging:
  level:
    xiao7.cloud.consumer.feign: DEBUG

feign:
  # Feign client configuration, corresponding to FeignClientProperties configuration property class
  client:
    # The config configuration item is of type Map.  The key is the name of the Feign client, and the value is the FeignClientConfiguration object
    config:
      # Global level configuration
      default:
        logger-level: BASIC
      # Client level configuration
      cloud-provider:
        logger-level: FULL

Through the FeignClientConfiguration configuration property class, we can see all the configuration items of FeignClient supported by the configuration file.
code show as below:

// Feign log level. Default is NONE
private Logger.Level loggerLevel;
// The requested connection timeout period, in milliseconds. Default is 10 * 1000 ms
private Integer connectTimeout;
// The requested read timeout, in milliseconds. Default is 60 * 1000 ms
private Integer readTimeout;
// Retry strategy. Default is no retry
private Class<Retryer> retryer;
// error decoder
private Class<ErrorDecoder> errorDecoder;
// request interceptor
private List<Class<RequestInterceptor>> requestInterceptors;
// Whether to decode when the response status code is 404. Default is false 
private Boolean decode404;
// decoder.
// When empty, SpringDecoder Bean is created by default
private Class<Decoder> decoder;
// decoder. Defaults to SpringEncoder
// When empty, SpringEncoder Bean is created by default
private Class<Encoder> encoder;
// contract.
// When empty, the SpringMvcContract Bean is created by default to provide support for SpringMVC annotations
private Class<Contract> contract;

Java Config way:

@Configuration
public class CloudConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean
    public Logger.Level defaultFeignClientLoggerLevel() {
        return Logger.Level.FULL;
    }
}

Just start the test

Tags: Java Spring Cloud

Posted by NoobPHP on Thu, 02 Jun 2022 04:42:05 +0530