Springboot integrates Feign to realize remote interface call

Ordinary is just two words: laziness and laziness;
success is just two words: hardship and diligence;
excellence is just two words: you and me.
Follow me to learn JAVA, spring family bucket and linux operation and maintenance knowledge from 0, and take you from an ignorant teenager to the peak of life, and marry Bai Fumei!
Follow the WeChat public account [  IT is very reliable  ], and share technical experience every day~

 

Springboot integrates Feign to realize remote interface call

      In javaweb projects, third-party interfaces (or other microservice interfaces) are often requested. There are many ways to implement remote interface calls, such as HttpURLConnection, restTemplate and spring-cloud-Feign toolkit provided in the spring-web package.
      Here I will take Feign as an example to explain the actual combat. It mainly includes the following knowledge points:
     1) The springboot project integrates Feign and implements remote interface calls through feign client;
     2) Configure interceptor to implement feign client to carry request header information when calling remote interfaces;
     3) Configure feign log configuration to implement logging Output request header, request body, response header, and response body information.

 

1 What is feign?

      Like Ribbon, Feign is also provided by Netflflix. Feign is a declarative and templated Web Service client, which simplifies the operation of developers to write Web service clients. Developers can use simple access and annotations. Call the HTTP API, Spring Cloud Feign, which integrates Ribbon and Hystrix, and has a series of convenient functions such as pluggable, annotation-based, load balancing, and service fusing.

 

2 Features of feign

      1) Feign is a declarative Web Service client.

      2) Support Feign annotations, Spring MVC annotations, JAX-RS annotations.

      3) Feign is implemented based on Ribbon, making it easier to use.

      4) Feign integrates Hystrix , with the function of service fuse downgrade.

 

3 Springboot project integrates feign

      Note: The creation of the springboot project will no longer demonstrate it. At this point, it is assumed that we have already created a springboot project named: feign-demo  .

      The springboot project structure is as follows:

3.1 Introduce jar dependency

      Add openfeign dependency in the project pom.xml file.

        <!--添加openfein的依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

 

3.2 Enable FeignClients

    在项目启动类上添加注解@EnableFeignClients允许开启Feign调用,并指定basePackages来扫描扫描@FeignClient注解标注的FeignClient接口。
@EnableFeignClients(basePackages = "com.hc.feigndemo")
public class FeignDemoApplication {

     ......

}

 

3.3 Define FeignClient interface

      定义用户client接口类:UserClient.java
package com.hc.feigndemo.client;

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

/**
 * 定义用户client接口
 */
@FeignClient(
    name = "USER-CLIENT",
    url = "http://localhost:8080/main/")
public interface UserClient {

  /**
   * 查询用户
   */
  @PostMapping(path = "/userInfo")
  String userInfo();
}

      So far, the springboot project has integrated feign. Let's test whether we can call the interface through the feign client.

 

3.4 Access FeignClient

     First we need to inject the bean object UserClient:

    @Autowired
    private UserClient userClient;

      Call the userInfo interface defined by userClient.

    /**
     * 查询用户信息
     * @return
     */
    @GetMapping("queryUserInfo")
    @ResponseBody
    public String queryUserInfo(){
        return userClient.userInfo();
    }

    /**
     * 模拟client远程调用的接口
     * @return
     */
    @PostMapping("userInfo")
    @ResponseBody
    public String userInfo(){
        return "my name is xxx";
    }

3.5 feignClient test results

      From the screenshot, the remote (third-party) interface is called through the feign client. But the request header does not carry interface permission verification information (such as clientId and clientSecret, etc.). Therefore, we need to configure an interceptor and add authorization verification information to all feign client request headers.

 

4 feign client request to add request header

4.1 Configure request interceptor

      Create an interceptor class that implements the RequestInterceptor interface: OpenApiRequestInterceptor.java , and add the request header information client-id and client-secret.

/**
 * 配置请求拦截器
 */
@Component
public class OpenApiRequestInterceptor implements RequestInterceptor {

  private String clientId = "clientId";
  private String clientSecret = "xxxxxx";

  /**
   * 给所有请求添加头信息client-id和client-secret
   * @param template
   */
  @Override
  public void apply(RequestTemplate template) {
    template
        .header("client-id", clientId)
        .header("client-secret", clientSecret);
  }
}

       So far, we have added client-id and client-secret request header information to all request headers of feign client. But we can't see what the request header information is. what else can we do? The answer is: log!

 

4 Feign log

      The feign log output is very necessary, it can help us analyze and locate problems in the production process. A few days ago, I also encountered a production problem: the test environment is always normal, but after the WeChat applet backend service went online, I found that a feign client interface reported 401 (authority verification failed). After investigation and adding the feign log, it was finally located that the request interface URL had a path symbol "/". It can be seen how important the feign log is, here is the basic configuration steps for feign log output.

4.1 Create Log Configuration Class

      Create a log configuration class: FeignLogConfiguration.java and specify the log level.

      Feign's log processing is very flexible. You can specify a logging strategy for each Feign client, and each Feign client will create a logger. By default, the name of the logger is the full class name of the Feigh interface. It should be noted that: Feign log printing will only respond to DEBUG level . We can configure various Logger.Level objects for each Feign client to tell Feign which logs to record.

      The values ​​of Logger.Level are:

      1) NONE: No record (DEFAULT).

      2) BASIC: Only record request method and URL, response status code and execution time.

      3) HEADERS: Record basic information and request and response headers.

      4) FULL: Record the header, body and metadata of the request and response.

package com.hc.feigndemo.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 定义FeignLogConfiguration日志级别配置类
 */
@Configuration
public class FeignLogConfiguration {

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

 

4.2 Specify the log level configuration class

 

4.3 Set feign interface log level

      Set the log level of the Feign interface to DEBUG, because Feign's Logger.Level only responds to DEBUG.

 

4.4 Restart the project to test whether the feign log takes effect

      Request interface.

       Check the console log, you can see that the request header, request body, response header, and response body of the feign client request are all printed. Mom no longer has to worry about my bugs, and easily locate the problem through the log information~

       Follow the WeChat public account and reply " I want feign integrated source code " to get the source code of this tutorial feign-demo project, java and related video tutorials for free~

Guess you like

Origin blog.csdn.net/IT_Most/article/details/109165951
Recommended