Function and use of OpenFeign

1. Steps for using openfeign

1.1 what is openfeign? What's the difference between him and Feign?

Feign is a declarative Web Service client. Its appearance makes it easy to develop Web Service clients. To use feign, you only need to create an interface and add corresponding annotations, such as FeignClient annotation. There are notes for fers and fers JA pluggable.
Feign also supports encoders and decoders. Spring Cloud Open Feign enhances feign, supports Spring MVC annotations, and can use HttpMessageConverters like Spring Web.
Feign is a declarative and templated HTTP client. Using feign in Spring Cloud, you can use HTTP requests to access remote services, just like calling local methods. Developers are completely unaware that they are calling remote methods, let alone accessing HTTP requests. (that's what it says on the official website)

To put it bluntly, you used to call the micro service interface through restTemplate.. Getforobject is called remotely, but you don't have to use resttemplate when Feign appears. You can call the local interface. OpenFegin supports spring MVC annotations such as requestMapping on the basis of Fegin. Both Fegin and OpenFegin support load balancing

1.2 import pom file

Add OpenFegin dependency to pom file.

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!----This one doesn't have a version number because I'm in my father's office pom It has been imported springcloud Common dependent uniform version number pom You don't have to import

1.3 yml documents

server:
  port: 80
eureka:
  client:
    register-with-eureka: false#Consumers do not need to register in eureka with OpenFegin provider
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka# Select the registered service provider from the 70017002 cluster.

1.4 main startup

@SpringBootApplication
@EnableFeignClients//Add this annotation to explain that Fegin is used
public class OrderFeginMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeginMain80.class,args);
    }
}

1.5 service class

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//Be sure to add this annotation. The value value indicates which service provider to find for the service name
public interface PaymentFeginService {
    @GetMapping(value = "/payment/get/{id}")//The path of the annotation should be the same as that of the controller providing the service
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);//Same as controller
}

1.6 controller class

@RestController
@Slf4j
public class PaymentFeginController {
    @Autowired
    private PaymentFeginService paymentFeginService;
    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id)
    {
        return paymentFeginService.getPaymentById(id);//Call directly through the service class rather than remotely through restTemplate
    }
}

Although this seems to be calling your local application, it is calling the service provided by you remotely, so you should ensure that your remote service provides corresponding functions

1.7 result display

1.8 summary and precautions

As like as two peas, you should add @EnableFeginClients to the consumer's startup class. Then you add a @FeginClient (service name) annotation to the consumer's service class. Then the parameters of the interface are exactly the same as the way you provide the service.

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//Be sure to add this annotation. The value value indicates which service provider to find for the service name
public interface PaymentFeginService {
    @GetMapping(value = "/payment/find/{id}")//I changed this path
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}

result:

2.OpenFeign timeout control

When a network timeout occurs in the process of accessing the service provider, a timeout error will be reported. For example, if I rewrite a method and do some delay operations before return, a timeout error will be reported

For example, add this method to the service provider, pause for 3s and return to serverPort

    @GetMapping(value = "/testTimeOut")
    public String TimeOutFeignTest(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

(OpenFegin configuration omitted)

The result is

There is a Read timed out error, so how can we extend the timeout? Just change the yml file

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
ribbon:
  ReadTimeout: 5000 #Just change him to 5s overtime
  ConnectTimeout: 5000

After the change, the result is

3.OpenFeign log printing function

3.1 what is OpenFeign log

Feign provides log printing function. We can adjust the log level through configuration to understand the details of Http requests in feign. To put it bluntly, it is to monitor and output the call of Fegin interface.

3.2 log level

NONE: default, no logs are displayed;

BASIC: only record the request method, URL, response status and execution time;

HEADERS: in addition to the information defined in BASIC, there are also header information of request and response;

FULL: in addition to the information defined in HEADERS, there are also the body and metadata of the request and response.

3.3 configuring log bean s

@Configuration
public class FeginConfig {
    @Bean
    Logger.Level feginLoggerLevel(){
        return Logger.Level.FULL;
    }
}

Add this paragraph to the yml document

logging:
  level:
    #What level does he monitor and which interface
    com.wjz.springcloud.service.PaymentFeginService: debug

By calling this interface, you can clearly see the information of HTTP call in the background


Reference: Shang Silicon Valley.

Keywords: Java Spring Boot Spring Cloud

Added by lee_umney on Tue, 08 Feb 2022 02:44:34 +0200