[SpringCloud component learning notes series] OpenFeign component

Posted by pb4life55 on Sat, 12 Feb 2022 12:54:34 +0100

3. Use and explanation of SpringCloud Netflix OpenFeign

Feign can hide the Rest request and disguise it as a Controller similar to spring MVC. It doesn't need to splice URL s, parameters and other operations by itself. Feign can take over these and complete them automatically.

3.1 use of Feign

3.1.1. Dependency import

In the pom file of consumer:

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

Create the client interface class, add the @ FeignClient annotation, and specify the service name to be accessed

/**
 * Feign Client configuration
 */
@FeignClient("User-Service") // User service is the micro service name of the service provider
public interface UserFeignClient {

    /**
     * Feign The implementation class will be generated through dynamic proxy
     * The interface with @ FeignClient annotation is added. All its abstract methods completely adopt the annotation of spring MVC. Feign will automatically generate the URL according to the annotation and access the results
     * getmapping The address given in must be preceded by a slash, because it needs to be spliced. Without a slash, the spliced address will be inaccessible
     */
    @GetMapping("/user/queryById/{id}") // feign processes the request address into http://user-service/user/queryById/id , very elegant
    public CommonVo<User> queryById(@PathVariable("id") Long id);
}
3.1.3. Write a new Controller
@RestController
@RequestMapping("/UserFeign")
public class UserByFeignController {

    @Autowired
    private UserFeignClient client; // Inject Feign's client for use

    @GetMapping("/user/queryById/{id}")
    public CommonVo<User> queryById(@PathVariable("id") Long id){
        CommonVo<User> userCommonVo = client.queryById(id);
        return userCommonVo;
    }
}
3.1.4 startup

Add comments to enable Feign * * @ EnabledFeignClients**

@SpringBootApplication//(exclude= {DataSourceAutoConfiguration.class}) //exclude avoid reporting errors because there are classes in other imported modules that need to link to the database
@EnableDiscoveryClient //Turn on Eureka client discovery
@EnableCircuitBreaker // Open fuse
@EnableFeignClients //Enable Feign function
public class SpringCloud_Consumer_80_Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloud_Consumer_80_Application.class,args);
    }
}
3.1.5 start service and test

3.2 load balancing

Feign integrates Ribbon dependency and automatic configuration, so it can directly support load balancing

The Ribbon built in Feign sets the request timeout length by default, which is 1000ms. You can modify this value by setting the parameter value.

3.2.1. Configure Global
ribbon: 
	ReadTimeout: 2000 # Read timeout length
	ConnectTimeout: 1000 # Timeout for establishing link
3.2.2. Configure a single service name
User-Service: 
  ribbon: 
    ReadTimeout: 2000 # Read timeout length
    ConnectTimeout: 1000 # Timeout for establishing link

User service is the service name of the service provider.

Ribbon has an internal retry mechanism. Once it times out, it will automatically re initiate a request.

These values can also be specified through the configuration file configuration.

3.2.3 other common configuration items
ribbon: 
	ConnectTimeout: 1000 # Connection timeout duration 
	ReadTimeout: 2000 # Data communication timeout duration 
	MaxAutoRetries: 0 # Number of retries for the current server 
	MaxAutoRetriesNextServer: 0 # How many service retries 
	OkToRetryOnAllOperations: false # Do you want to retry all request methods

3.3. Hystrix support

3.3.1. Turn on Hystrix

Feign integrates Hystrix, but it is turned off by default and needs to be turned on in the configuration file.

feign: 
	hystrix: 
		enabled: true # Turn on the fusing function of Feign
3.3.2. Use Hystrix

Write the implementation class of Feign client

/**
 * Write the implementation class of Feign client, which is used to process the request with fuse
 */
@Component
public class UserFallBack implements UserFeignClient{
    /**
     * Process the queryById request address. When the request expires, call the following method to respond to the client
     * @param id
     * @return
     */
    @Override
    public CommonVo<User> queryById(Long id) {
        return new CommonVo<>(400,"Sorry, Unicom Network reminds you that the service you requested is temporarily unavailable. Please try again later!!!",null);
    }
}

In the modified client, the value of the fallback attribute of the @ FeignClient annotation is the custom implementation class of the interface

/**
 * Feign Client configuration
 */
@FeignClient(value = "User-Service",fallback = UserFallBack.class) // User service is the micro service name of the service provider
public interface UserFeignClient {

    /**
     * Feign The implementation class will be generated through dynamic proxy
     * The interface with @ FeignClient annotation is added. All its abstract methods completely adopt the annotation of spring MVC. Feign will automatically generate the URL according to the annotation and access the results
     * getmapping The address given in must be preceded by a slash, because it needs to be spliced. Without a slash, the spliced address will be inaccessible
     */
    @GetMapping("/user/queryById/{id}") // feign processes the request address into http://user-service/user/queryById/id , very elegant
    public CommonVo<User> queryById(@PathVariable("id") Long id);
}
3.3.3 difference before and after test

Open consumer, provider and Eureka services

Normal access:

After stopping the service provider, access:

At this time, the service degradation is triggered, and the subclass method of Feign client configuration class specified by fallback is called.

3.4. Request compression (understand)

Spring Cloud Feign supports GZIP compression of requests and responses to reduce performance loss during communication. The compression function of request and response can be enabled through the following parameters:

feign: 
	compression: 
		request: 
			enabled: true # Turn on request compression 
		response: 
			enabled: true # Turn on response compression

At the same time, we can also set the requested data type and the lower limit of the size to trigger compression:

feign: 
	compression: 
		request: 
			enabled: true # Turn on request compression 
			mime-types: text/html,application/xml,application/json # Set compressed data type 
			min-request-size: 2048 # Sets the lower limit of the size that triggers compression

Note: the above are the default values.

3.5 log level (understand)

After setting the log level, you can see the specific information of compression on the console.

@FeignClient annotation: a new FeignClient will be created when the modified client is proxied Logger example. You need to specify the log level of this instance. Print log completed.

3.5.1. Set log level
logging: 
	level: 
		com.aliang: debug # com. Alias is the package name
3.5.2. Write Feign configuration class
/**
 * Feign Log configuration class for
 */
@Configuration
public class FeignConfiguration {

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

The Level specified here is FULL. Feign supports four levels:

  • NONE: no log information is recorded, which is the default value.
  • BASIC: only record the requested method, URL, response status code and execution time
  • HEADERS: on the basis of BASIC, additional header information of request and response is recorded
  • FULL: records the details of all requests and responses, including header information, request body and metadata.
3.5.3 specify configuration class
/**
 * Feign Client configuration
 */
// User service is the micro service name of the service provider
@FeignClient(value = "User-Service",fallback = UserFallBack.class,configuration = FeignConfiguration.class)  //Configuration specifies the configuration class
public interface UserFeignClient {
    @GetMapping("/user/queryById/{id}") 
    public CommonVo<User> queryById(@PathVariable("id") Long id);
}
3.5.4 test

The browser inputs the address and the console outputs the following information:

Topics: Java Spring Spring Cloud