Understanding and application of SpringCloud-Feign

Feign

Introduction

Spring Cloud introduces Feign and integrates Ribbon to implement client load balancing calls. Feign is a lightweight rest client that simplifies remote calls and makes remote calls like local methods.

Feign steps

1. Introduce coordinates
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
2. Configure the annotation @EnableFeignClients on the startup class to scan, generate proxy objects, and inject into the IOC container
@SpringBootApplication
@EnableFeignClients
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class);
    }
}
3. Add the configuration file as shown below

Insert picture description here

3. Define an interface and add FeignClient annotations to declare the service name to be called remotely (all service names are written in the public class)

Insert picture description here
Insert picture description here

4. Define FeignController to call the test

Insert picture description here

5. Start each related service test

Service registered to the registry
Insert picture description here
test results
Insert picture description here

Now that Feign integrates Ribbon, how to use it?

In fact, after the above steps are completed, the default polling load balancing strategy has been adopted. If you want to change a strategy, how to solve it? (use your brain)

Feign also integrates Hystrix, how to use it?

1. Add the following to the configuration file to enable the Hystrix function

Insert picture description here

2. Set the callback class on the interface class

Insert picture description here

3. The MyFallback class is shown below

Insert picture description here

How to obtain abnormal information of remote service

1. Modify the annotation parameters on the interface class as shown below

Insert picture description here

2. Define the MyFallbackFactory class as follows

Insert picture description here

3. Start the service test (omitted)

Precautions

SpringCloud enhanced Feign to be compatible with SpringMVC annotations. We need to pay attention when using SpringMVC annotations:

When the 1feignClient return value is a complex object, its type must have a parameterless constructor.

Guess you like

Origin blog.csdn.net/mrhs_dhls/article/details/107899982
Recommended