Spring cloud lecture 07: Http templating client Feign

Feign is a declarative and templated HTTP client developed by Netflix. Feign can help us call microservices more quickly and gracefully.

1, Item code

The service consumer content center sends a request to the service provider user center to obtain the user's wechat nickname. We realize this requirement through Feign.

1.1. In POM Adding dependencies to XML

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

1.2. Add @ EnableFeignClients annotation in BootApplication

package com.itmuch.contentcenter;

import org.springframework.cloud.openfeign.EnableFeignClients;
...

@SpringBootApplication
@EnableFeignClients
public class ContentCenterApplication {
...
}

1.3. Create Feign client to realize Feign remote request

package com.itmuch.contentcenter.feignclient;

import com.itmuch.contentcenter.domain.dto.user.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "user-center")//Name of the microservice
public interface UserCenterFeignClient {
    /**
     * Feign The URL is automatically built http://user-center/users/{id}
     * @param id
     * @return
     */
    @GetMapping("/users/{id}")
    UserDTO findById(@PathVariable Integer id);
}

The method can be implemented in Service.

2, Feign custom log level

levelprint contents
NONE (default)No logs are logged
BASICOnly the request method, URL, request status code and execution time are recorded
HEADERSBased on the BASIC level, record the header s of requests and responses
FULLRecord the header, body and metadata of the request and response

2.1. In application YML add attribute

In application Add attributes in YML in combination with log

#Set log output level
logging:
  level:
    com.itmuch.contentcenter.feignclient.UserCenterFeignClient: debug
feign:
  client:
    config:
      #The name of the micro service you want to call
      user-center:
        loggerLevel: full

2.2 test effect

3, Configuration items supported by Feign

Configuration itemeffect
Logger.LevelSpecify log level
RetryerSpecify retry policy
ErrorDecoderSpecify error decoder
Request.OptionsTimeout
Collection<RequestInterceptor>Interceptor
SetterFactoryIt is used to set the configuration properties of Hystrix. It can only be used when Feign integrates Hystrix

 application.yml configuration reference

4, Multi parameter request

Multiparameters can be implemented using the @ SpringQueryMap annotation

package com.itmuch.contentcenter.feignclient;

import com.itmuch.contentcenter.domain.dto.user.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "user-center")
public interface TestUserCenterFeignClient {
    @GetMapping("/q")
    UserDTO query(@SpringQueryMap UserDTO userDTO);
}

Note that multiple Feign interfaces may access the same microservice during development. Solutions:

In application Add attribute configuration in YML

spring:
  #Solve the problem that Feign multiple Client interfaces point to the same microservice
  main:
    allow-bean-definition-overriding: true

5, Use Feign separately from Nacos

5.1. Create FeignClient and request Baidu

package com.itmuch.contentcenter.feignclient;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "baidu", url = "http://www.baidu.com")
public interface TestBaiduFeignClient {
    @GetMapping("")
    public String index();
}

5.2, calling FeignClient method in test Controller.

@Autowired
private TestBaiduFeignClient testBaiduFeignClient;

@GetMapping("baidu")
public String baiduIndex(){
    return testBaiduFeignClient.index();
}

5.3 test effect

Vi. comparison between RestTemplate and Feign

angleRestTemplateFeign
Readability and maintainabilitycommonlyvery good
Development experiencePoorvery good
performancevery goodMedium (about 50% of RestTemplate, but you can use connection pool to improve performance by 15%)
flexibilityvery goodMedium (built-in function can meet most requirements)

7, Performance optimization of Feign

7.1. Use connection pool to improve performance by 15%

pom. Adding dependencies to XML

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

application. Add attribute to YML to configure connection pool

feign: 
  httpclient:
    #Let feign use Apache httpclient for requests instead of the default urlconnection
    enabled: true
    #Maximum connections for feign
    max-connections: 200
    #feign maximum number of connections for a single path
    max-connections-per-route: 50

7.2. Set the log level to basic and do not use full

feign:
  client:
    config:
      #The name or global configuration of the microservice you want to call
      default:
        loggerLevel: basic

8, Summary of Feign's frequently asked questions

reference resources: https://www.imooc.com/article/289005

Special announcement: this series of tutorials (spring cloud Alibaba) refer to the online video courses provided by zimuke.com. Students in need can search and learn by themselves

Keywords: Java Spring Cloud http springcloudalibaba

Added by ramesh_iridium on Wed, 19 Jan 2022 18:30:07 +0200