preface

Spring Cloud OpenFeign is an updated version of Feign, which is currently available on Github with 11.6. Feign is a declarative, templatable HTTP client developed by Netflix. Feign allows us to call the HTTP API more quickly and gracefully.

One, OpenFeign configuration use

The use of OpenFeign must first depend on the Spring Cloud, which is essential for the Alibaba microservices architecture.

1. Introduce POM dependencies

<! - openfeign service call - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code

2. Start Feign service invocation on the consumer

Invoke the inventory server’s interface methods by starting Feign’s service call on the dT-order-Servic initiator.

EnableFeignClients: Enable service invocation

3. Dynamic proxy Service interface on the consumer

@FeignClient(name = "dt-stock-service",path = "/stock")
public interface StockFeignService {
    
    @GetMapping(value = "/getPort")
    String getPort(a);
}
Copy the code

@FeignClient(name = “dt-stock-service”,path = “/stock”)

Dt-stock-service: service name of the service provider. Path: uniform prefix of the service provider.

3. Consumer side testing

Write a controller that calls the service exposure interface method:

2. OpenFeign Log configuration

By default, OpenFeign’s logging is disabled. During development, we need to debug the interface or check the performance of calls. We need to configure OpenFeign’s logging to print out the call logs clearly for our development.

Feign Log level:

NONE: no record (DEFAULT). BASIC, which records only the request method and URL and the response status code and execution time. HEADERS records basic information and request and response HEADERS. FULL, which records the header, body, and metadata of the request and response

1. Log global configuration

OpenFeignConfig.class

/** * Global configuration: global log configuration for OpenFeign * Local configuration: not added@ConfigurationComment *@author DT
 * @date2021/8/9 22:00 * /
@Configuration
public class OpenFeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel(a){
        // Output log level FULL
        returnLogger.Level.FULL; }}Copy the code

The default SpringBoot log level is info, which is greater than full. As a result, feign’s log configuration is not output.

The default log level of SpringBoot is info, which is greater than full, so feign's log configuration is not output
logging:
  level:
    com.dt.springcloud.openfeign: debug
Copy the code

Output print:

2. Configure logs for a single service

Use configuration = OpenFeignConfig.class

Of course, we can also use configuration files to configure.

3. Configure logs in the configuration file

1. Global configuration

For all service configurations:

The default log level of SpringBoot is info, which is greater than full, so feign's log configuration is not output
logging:
  level:
    com.dt.springcloud.openfeign: debug
Feign Log global configuration
feign:
  client:
    config:
      default:
        loggerLevel: BASIC
Copy the code

2. Configure a service separately

You can also configure a separate log for a service, and change the microservice name to default to make it global:

Feign Configures logs for a service
feign:
  client:
    config:
      # Name of the microservice you want to invoke
      dt-stock-service:
        loggerLevel: BASIC
Copy the code

OpenFeign custom interceptor

The OpenFeign interceptors, just like our SpringMVC interceptors, execute the interceptor logic before each HTTP call is made by Feign, such as adding headers and changing or replacing information in the body. Feign provides the Feign.RequestInterceptor interface. By implementing this interface, implementing the corresponding methods, and handing the implementation class to the Spring container via @Configuration, we can add our own generic processing logic.

1. Global configuration

@CommonsLog
@Configuration
public class CustomFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("token"."ABC123456");
        byte[] body = requestTemplate.body();
        String url = requestTemplate.url();
        String method = requestTemplate.method();
        Map<String, Collection<String>> map = requestTemplate.headers();
        log.info("OpenFeign interceptor starts......");
        log.info("body->>>"+(body == null ? null : body.length));
        log.info("url->>>"+url);
        log.info("method->>>"+method);
        log.info("header->>>"+map.get("token")); }}Copy the code

To view the print:

If you need to do something else, you can do it with the RequestTemplate, such as token validation, refresh, authentication, and so on.

2. Configure a service separately

In addition to the first global configuration above, we can also configure the invoked service separately in the configuration file, just as we did with the logging configuration above.

Feign configures for a service
feign:
  client:
    config:
      # Name of the microservice you want to invoke
      dt-stock-service:
        connectTimeout: 5000  # Connection timeout
        readTimeout: 5000     # Read timeout
        loggerLevel: BASIC
        requestInterceptors: This is the same as the RequestInterceptor in the code configuration
          - com.dt.springcloud.interceptor.CustomFeignInterceptor
Copy the code

Dt-stock-service Specifies the name of the service you want to invoke.

conclusion

No one’s luck, it comes from nowhere, only when you work hard enough, you will be lucky enough. The world will not disappoint every effort and persistence, time will not neglect persistent and brave everyone

This article is over, we will continue to further study the use of other components of micro-services and principle analysis, creation is not easy, like please pay attention to small series CSDN: blog.csdn.net/qq_41107231 and nuggets: juejin.cn/user/394024…