Introduction to Feign
Feign is a lightweight RESTful HTTP service client developed by Netflix (using it to initiate requests and remote calls). It calls Http requests in Java interface annotations, rather than calling directly by encapsulating HTTP request messages like in Java. Feign is widely used in Spring Cloud's solution. Similar to Dubbo, the service consumer gets the service provider's interface and then calls it like calling the local interface method, which actually sends a remote request.
Feign helps us to call HTTP API more conveniently and elegantly: we don’t need to splice the url and then call the restTemplate API. In SpringCloud, using Feign is very simple. Create an interface (on the consumer-service caller side), and add some annotations on the interface, and the code is completed.
SpringCloud has enhanced Feign, making Feign support SpringMVC annotation (OpenFeign). In essence: it encapsulates the Http call process and is more in line with the interface-oriented programming habits. Similar to Dubbo's service call, Dubbo's calling method is actually good interface-oriented programming.
💻It is a declarative (annotated) web service client
To use Feign, you need to create an interface and annotate it. It is a remotely called component (interface, annotation) called http💻Feign integrates ribbon ribbon integrates eureka
use
Similar to the case of Ribbon in the previous article, it also allows clients to access and help each other.
Implementation: Two merchants, one intermediary and one provider. The user accesses the intermediary's interface, and the intermediary sends a request to the provider to create it.
I also created two clients, but I won't go through the process before.
I've created aorder-service-01
And oneuser-service-02
order-service-01: Provider
Configuration file configuration:
server: port: 8080 spring: application: name: order-service eureka: client: service-url: defaultZone: Your remoteeurekaaddress
Start the client
@EnableEurekaClient
Write a controller for order delivery
@RestController public class OrderControll { @GetMapping("doOrder") public String doOrder(){ return "Making noodles"; } }
Just start
user-service-02: Intermediary
Key dependencies:
<!-- feignrely--> <dependency> <groupId></groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
Configuration File:
server: port: 8081 spring: application: name: user-service eureka: client: service-url: defaultZone: Your remoteeurekaaddress
Start the service
@EnableFeignClients: enable feign
@EnableDiscoveryClient @EnableFeignClients
Key: Create an interface classUserOrderfeign
You need to call the doOrder interface of the provider (order-service) that is, you can write it in the code below.
/** * Notes below: * value is the provider's application name */ @FeignClient(value="order-service") public interface UserOrderfeign { /** * Write the method signature of the controller you need to call * @return */ @GetMapping("doOrder") String doOrder(); }
writecontroller
Implementation Class
Directly introduce the written userOrderfeign to directly call the provider's interface
@RestController public class UserControll { @Autowired public UserOrderfeign userOrderfeign; @GetMapping("userDoOrder") public String userDoOrder(){ ("Customer is here..."); //Start a remote call String str=(); return str; } }
After running the final access to localhost:8081/userDoOrder page, the content returned by the provider will be displayed~
Transfer the ginseng
It is necessary to ensure that the parameter list is consistent, the return value is consistent, and the method signature is consistent
- URL parameter transfer: Use parameter list
@PathVariable
- GET parameter transfer: Use parameter list
@RequestParam
- POST parameter transfer: Use parameter list
@RequestParam
orRequestbody
Continue to use based on the above example
order-service
How to write a controller
URL splicing parameters
//url splicing parameters @GetMapping("testUrl/{name}/and/{age}") public String testUrl(@PathVariable("name")String name,@PathVariable("age")Integer age){ (name+":"+age); return "ok"; }
GET Transfer
//url passes a parameter @GetMapping("oneParam") public String oneParam(@RequestParam String name){ (name); return "ok"; } //url passes multiple parameters @GetMapping("twoParam") public String twoParam(@RequestParam(required = false) String name,@RequestParam(required = false)Integer age){ (name); (age); return "ok"; }
POST parameter transfer
Write entity class order
Used here
lambok
Implement automatic addition of parameters without parameters set, get and other methods
@Data @AllArgsConstructor @NoArgsConstructor @Builder public class Order { private Integer id; private String name; private Double price; private Date time; }
//Post request to pass an object @PostMapping("oneObj") public String oneObj(@RequestBody Order order){ (order); return "ok"; } //Post request passes an object and a parameter @PostMapping("oneObjOneParam") public String oneObjOneParam(@RequestBody Order order,@RequestParam("name")String name){ (order); (name); return "ok"; }
Call
user-service
Write parameter transfer method of control class in feign interface
/urlSplicing grammar @GetMapping("testUrl/{name}/and/{age}") public String testUrl(@PathVariable("name")String name, @PathVariable("age")Integer age); //url passes a parameter @GetMapping("oneParam") public String oneParam(@RequestParam String name); //url passes multiple parameters @GetMapping("twoParam") public String twoParam(@RequestParam(required = false) String name,@RequestParam(required = false)Integer age); //Post request to pass an object @PostMapping("oneObj") public String oneObj(@RequestBody Order order); //Post request passes an object and a parameter @PostMapping("oneObjOneParam") public String oneObjOneParam(@RequestBody Order order,@RequestParam("name")String name);
user-service
Write method calls in the controller
@GetMapping("testParam") public String testParam(){ String zt = ("zt", 21); (zt); String xzl = ("xzl"); (xzl); String wf = ("wf", 22); (wf); Order order= () .name("steak") .price(188D) .time(new Date()) .id(1) .build(); String s = (order); (s); String param = (order, "dqf"); (param); return "ok"; }
The above can realize the transmission of parameters~
expand
Feign's default waiting time is 1s. If it exceeds 1s, it will directly report an error timeout.
Configure timeout, connection time
Tip:
feign only encapsulates the function of remote calls. The underlying layer is still ribbon, so the time of ribbon needs to be modified
#feign just encapsulates the function of remote calls. The underlying layer is still ribbon, so the time of ribbon needs to be modifiedribbon: ReadTimeout: 3000 #3s timeout time ConnectTimeout: 3000 #Timeout for connection service
Log printing
Writing logging is conducive to error checking
Log Level
NONE
:Default, no logs are displayed;
BASIC
: Only record the request method, URL, response status code and execution time;
HEACIERS
: In addition to the information defined in BASIC, there are also request and response header information
FULL
:In addition to the information defined in HEADERS, there are also the body and metadata of the request and response.
In the startup classapplication
Written in
/** * Print log information */ @Bean public level(){ return ; }
In the configuration fileyml
Open the log client
logging: level: .: debug # Need to print the log requesting this interface...
The path to the feign interface is below level
This allows users to access the interface to realize corresponding log printing related information
This is the end of this article about the use of Spring Cloud Feign. For more information about using Spring Cloud Feign, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!