Spring Cloud (7): OpenFeign service interface call

1 Overview

Feign is a declarative WebService client. Using Feign can make it easier to write a WebService client.

Its use is to define a service interface and add annotations on it. Feign also supports pluggable encoders and decoders. Spring Cloud encapsulated Feign to support Spring Mvc standard annotations and HttpMessageConverters. Feign can be used in combination with Eureka and Ribbon to support load balancing.

Source address: https://github.com/spring-cloud/spring-cloud-openfeign

1.1 What can be done

Feign aims to make it easier to write a Java Http client.
When using Ribboon+RestTemplate before, we used RestTemplate to encapsulate the http request to form a set of templated invocation methods. However, in actual development, since there may be more than one call to the service dependency, one interface is often called in multiple places. , So usually for each microservice, some client classes are packaged to package these dependent service calls. Therefore, Feign further encapsulates on this basis, and it helps us define and implement the definition of dependent service interfaces. Under the implementation of Feign, we only need to create an interface and use annotations to configure it (previously, the Dao interface was marked with @Mapper annotation, now it is a microservice, just deduct a Feign annotation on it). The interface binding of the service provider simplifies the amount of development of automatically encapsulating the service call client when using Spring cloud Ribbon.

Feign integrates Ribbon:
Use Ribbon to maintain the payment service list information, and implement load balancing of the client through polling. Unlike Ribbon, only the service binding interface needs to be defined through feign and in a declarative way, which is elegant The simple realization of the service call.

The difference between Feign and OpenFeign:

Feign OpenFeign
Feign is a lightweight RESTful HTTP service client in the Spring Cloud component. Feign has built-in Ribbon, which is used for client load balancing to call the service of the service registry. The method of using Feign is: use Feign's annotation definition Interface, call this interface, you can call the service of the service registry OpenFeign is that Spring Cloud supports SpringMVC annotations on the basis of Feign, such as @RequestMapping, etc. OpenFeign's @FeignClient can parse the interfaces under SpringMVC's @RequestMapping annotations, and generate implementation classes through dynamic proxying, which are done in the implementation classes. Load balance and call other services
  • feign:
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
  • openfeign:
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2. Steps to use OpenFeign

2.1 Interface + Annotation

Microservice call interface +@FeignClient

2.2 New cloud-consumer-feign-order80

Feign is used on the consumer side

2.3 pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-demo</artifactId>
        <groupId>com.lele.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-feign-order80</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.lele.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2.4 yml

server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

2.5 Main Startup Class

package com.lele.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author: lele
 * @date: 2021/3/17 7:27
 * @description:
 */
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

2.6 Business

Business logic interface + @FeignClient configuration call provider service

Create a new PaymentFeignService interface and add an annotation @FeignClient

package com.lele.springcloud.service;

import com.lele.springcloud.entities.CommonResult;
import com.lele.springcloud.entities.Payment;
import feign.Param;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author: lele
 * @date: 2021/3/17 7:31
 * @description:
 */
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    
    

    @GetMapping(value = "/payment/get/{id}")
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}

2.7 Controller

package com.lele.springcloud.controller;

import com.lele.springcloud.entities.CommonResult;
import com.lele.springcloud.entities.Payment;
import com.lele.springcloud.service.PaymentFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: lele
 * @date: 2021/3/17 7:39
 * @description:
 */
@RestController
@Slf4j
public class OrderFeignController {
    
    

    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
    
    
        return paymentFeignService.getPaymentById(id);
    }
}

2.8 Testing

  • Start Eureka cluster 7001, 7002 first
  • Start 8001, 8002
  • Start cloud-consumer-feign-order80
  • 访问:http://localhost/consumer/payment/get/1

Feign comes with load balancing configuration items

Insert picture description here

3. OpenFeign timeout control

  • 8001 PaymentController
    Insert picture description here

  • 80 PaymentFeignService
    Insert picture description here

  • 80 OrderFeignController
    Insert picture description here

  • Start 7001, 7002

  • Start 8001

  • Start feign80
    visit: http://localhost/consumer/payment/feign/timeout
    Insert picture description here

OpenFeign waits for one second by default, but the server processing takes more than one second, which makes the Feign client no longer want to wait and directly returns an error. In order to avoid this situation, sometimes it is necessary to set the timeout control of the Feign client.

Open in the yml configuration file:
Insert picture description here

# 设置feign客户端超时时间(openfiegn默认支持riboon)
ribbon:
  # 建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
  # 建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000
  • Restart feign80
  • 访问:http://localhost/consumer/payment/feign/timeout
    Insert picture description here

4. OpenFeign log printing function

4.1 What is

Feign provides a log printing function, we can adjust the log level through configuration, so as to understand the details of the Http request in Feign.
That is, to monitor and output the invocation of the Feign interface.

4.2 Log level

  • NONE: No log is displayed by default;
  • BASIC: Only record the request method, URL, response status code and execution time;
  • HEADERS: In addition to the information defined in BASIC, there are request and response header information;
  • FULL: In addition to the information defined in HEADERS, there are also the body and metadata of the request and response;

4.3 Configure logging bean

Insert picture description here

4.4 Feign clients that need to enable logs in YML files

Insert picture description here

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.lele.springcloud.service.PaymentFeignService: debug

访问:http://localhost/consumer/payment/get/1

Insert picture description here

Guess you like

Origin blog.csdn.net/houwanle/article/details/114914778