Practical application of OpenFeign

The development history of OpenFeign

(时光轴懒得画了,文字描述一下,有兴趣的自行百度下)
1) Ribbon is a load balancing tool based on HTTP and TCP clients. It can configure RibbonServerList (server list) on the client side, and use HttpClient or RestTemplate to simulate http requests. The steps are quite cumbersome.
2) Feign is an improvement on the basis of Ribbon, and it is a more convenient HTTP client to use. Using the interface method, you only need to create an interface, and then add annotations on it, and define the methods of other services that need to be called as abstract methods, without the need to construct http requests yourself.
3) OpenFeign is that Spring Cloud supports SpringMVC annotations on the basis of Feign, such as @RequestMapping and so on. OpenFeign's @FeignClient can parse the interface under SpringMVC's @RequestMapping annotation, and generate an implementation class through a dynamic proxy, implement load balancing and call other services in the implementation class.

load balancing

1) Centralized load balancing
即在 consumer 和provider 之间使用独立的负载均衡设施(比如nginx等,通过某种策略转发给provider )
insert image description here
2) In-process load balancing
将负载均衡逻辑集成到consumer, consumer从注册中心获知有那些地址可以用,然后自己再从这些地址中选择出一个合适的 privider
insert image description here
3) What is the difference between the two?

  • Centralized load balancing, there is an independent load balancing server deployed between the client and the service, which accepts requests and assigns them to different services
  • Process-based load balancing, integrating the load balancing logic into the consumer. The consumer learns which services are available from the registration center, and then uses the service according to the load balancing strategy

Three elements of OpenFeign

  • Registration Center (Proxy Interface Registration)
  • Client (call interface)
  • Service Provider (actual interface)

Registration Center (provided by nacos)

insert image description here

client

1) Define the service interface

  • ResourceFeignClient interface class (@FeignClient and fallbackFactory configuration)
    insert image description here
  • ResourceFeignClientFallback implementation class (FallbackFactory)insert image description here
  • Dependent service
    insert image description here
    2) OpenFeign dynamic proxy process
    insert image description here

Server

(提供扫描接口所在包路径和接口发现注解)
insert image description here

Notes on interface calls

  • 当参数比较复杂时,feign即使声明为get请求也会强行使用post请求(推荐均使用 post 请求方式);
  • 使用实体类进行传参时,请求方式不能为 Get ,若参数有其他类型变量时,则必须使用 @RequestBody;
  • 使用多个普通变量进行传参时,需配合@RequestParam进行使用,单个变量则不需要;
  • 当同时使用实体类和普通变量进行传参时,请求方和服务方的实体类都得使用 @RequestBody 注解,否则服务方的实体类无法接收请求方实体类参数值;
  • @RequestBody 和 @RequestParam 可以同时使用,但是请求方式必须是 post ;
  • 服务方使用实体类接收参数时,请求方可以定义该实体类内的各个变量,feign会将其一一映射,但必须使用 @RequestParam注解申明变量;

Guess you like

Origin blog.csdn.net/qq_23845083/article/details/129730414