day3 Feign remote call

In the previous study, we used Ribbon's load balancing function, which greatly simplified the code for remote calls:

If you learn this, you may need to write a lot of similar repetitive code in the future, the format is basically the same, but the parameters are different. Is there a more elegant way to optimize these codes again?

This is the Feign function we will learn next.

 

2.1. Introduction (configured in the ly-consumer microservice group)

Why is it called disguise?

Feign can hide the request of Rest and pretend to be a Controller similar to SpringMVC . You don't need to splice URLs, splicing parameters and so on by yourself, and leave everything to Feign to do.

 

2.2. Quick start

2.2.1. Import dependencies

First of all, this is an interface, Feign will use dynamic proxy to help us generate implementation classes. This is very similar to mybatis mapper

@FeignClient declares that this is a Feign client, similar to the @Mapper annotation. At the same time, specify the service name through the value attribute

The definition method in the interface completely adopts SpringMVC annotations. Feign will help us generate URLs based on the annotations and access the results.

 

2.2.3. Turn on Feign function

We add annotations on the startup class to enable Feign function

@EnableFeignClients // Enable Feign function

 

2.2.4. Start test:

 

2.3. Load balancing

 

Feign itself has integrated Ribbon dependency and automatic configuration:

Therefore, we do not need to introduce additional dependencies, nor do we need to register RestTemplate objects.

In addition, we can configure Ribbon as mentioned in the previous lesson, and we can configure it globally through ribbon.xx. You can also configure the specified service through the service name.ribbon.xx:

user-service:

  ribbon:

    ConnectTimeout: 250 # 连接超时时间(ms)

    ReadTimeout: 1000 # 通信超时时间(ms)

    OkToRetryOnAllOperations: true # 是否对所有操作重试

    MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数

    MaxAutoRetries: 1 # 同一实例的重试次数

 

Guess you like

Origin blog.csdn.net/qq_42198024/article/details/107904221