What is feign
Feign is a declarative pseudo HTTP client provided by spring cloud. It makes calling remote services as simple as calling local services. It only needs to create an interface and add a one-day annotation.
Nacos is well compatible with feign. Feign inherits ribbon by default, so load balancing is achieved by using feign default under Nacos.
Load balancing strategy supported by ribbon
Load balancing is to allocate requests to multiple instances for processing.
According to the location of load balancing, it is generally divided into server-side load balancing and client-side load balancing.
Server side load balancing refers to the service provider side, such as the common nginx load balancing.
Client load balancing refers to the side of the service request, which instance has been selected to process before the service request.
In microservices, we usually choose the client load balancing, and ribbon is the load balancing on the client.
Ribbon has a variety of built-in load balancing strategies. The top-level interface of internal load balancing is as follows: com.netflix.loadbalancer . iRule. The specific load strategy is shown in the following figure:
How to use feign
Using the Nacos discovery server in Chapter 1 as the service provider, we provide an interface of “/ Hello”. Create a new Alibaba client feign service as a consumer.
- If openfeign is dependent on POM file
- Add feign support annotation on the startup class
@Enable feign clients / / enable feign
- Create a feign client and use feign to call microservices
String hello(@RequestParam String name);
Note: in actual development, feign clients are written in the public module, which service needs to be called and introduced into the public module.
Two ways to realize feign
- The first one is introduced in this paper,Feign is consistent with the requestmapping of the producer。
- The second is to provide all the requested interfaces in the feign client, and then the controller implements the feign client, so it is unnecessary to write duplicate code.
- The request parameter is an object, using @ requestbody
- When the request parameter is received with @ requestparam, the value attribute must be added, such as @ requestparam (“name”)
- When the request parameter is received with @ pathvariable, the value attribute, such as @ pathvariable (“name”), must be added