Use Spring Cloud Feign as an HTTP client to call remote HTTP Services (recommended), cloudfeign

Source: Internet
Author: User

Use Spring Cloud Feign as an HTTP client to call remote HTTP Services (recommended), cloudfeign

In the Spring Cloud Netflix stack, each microservice exposes its own service in the form of an HTTP interface. Therefore, you must use an HTTP client when calling a remote service. We can use JDK native URLConnection, Apache Http Client, Netty asynchronous HTTP Client, and Spring RestTemplate. However, Feign is the most convenient and elegant to use.

Feign Introduction

Feign is a declarative and templated HTTP client. When Feign is used in Spring Cloud, we can achieve the same encoding experience as calling local methods when using HTTP to request remote services. Developers cannot perceive this remote method, it is not even aware that this is an HTTP request. For example:

@ Autowiredprivate AdvertGropRemoteService service; // remote service public AdvertGroupVO foo (Integer groupId) {return service. findByGroupId (groupId); // call remote service through HTTP}

Developers passservice.findByGroupId()It can complete the process of sending HTTP requests, decoding HTTP return results, and encapsulating them into objects.

Feign Definition

To let Feign know which address to send a request and what parameters should be included in the request when calling the method, we need to define an interface:

@FeignClient(name = "ea") // [A]public interface AdvertGroupRemoteService { @RequestMapping(value = "/group/{groupId}", method = RequestMethod.GET) // [B] AdvertGroupVO findByGroupId(@PathVariable("groupId") Integer adGroupId) // [C] @RequestMapping(value = "/group/{groupId}", method = RequestMethod.PUT) void update(@PathVariable("groupId") Integer groupId, @RequestParam("groupName") String groupName)

A: @ FeignClient is used to notify the Feign component to proxy this interface (no interface implementation is required). You can directly inject the interface through @ Autowired.

B: @ RequestMapping indicates that/group/{groupId}Send a GET request.

C: @ PathVariable has the same meaning as the annotation in SpringMVC.

When a Spring Cloud application is started, Feign scans the interface marked with @ FeignClient annotation to generate a proxy and registers it to the Spring container. When a proxy is generated, Feign creates a RequetTemplate object for each interface method, which encapsulates all the information required by the HTTP request, the request parameter name, request method, and other information are determined in this process. The templatification of Feign is embodied here.

In this example, we use Feign in combination with Eureka and Ribbon.,@FeignClient(name = "ea")It means to notify Feign to query the service named ea in Eureka when calling this interface method to obtain the service URL.

Feign Encoder, Decoder, and ErrorDecoder

Feign serializes the method parameter object in the method signature into a request parameter in an HTTP request, which is completed by the Encoder. Likewise, Decoder deserializes HTTP response data into java objects.

By default, Feign will convert the parameter marked with @ RequestParam annotation into a string and add it to the URL. The parameter without annotation is converted to json by Jackson and put in the request body. Note: If the method in @ RequetMapping specifies the request method as POST, all unannotated parameters will be ignored. For example:

@RequestMapping(value = "/group/{groupId}", method = RequestMethod.GET)void update(@PathVariable("groupId") Integer groupId, @RequestParam("groupName") String groupName, DataObject obj);

In this case, because the GET request does not have a request body, the obj parameter is ignored.

In the Spring Cloud environment, Feign's Encoder * is only used to encode parameters without Annotations *. If you customize Encoder, your Encoder will be called only when the obj parameter is encoded. For Decoder, It is delegated to the MappingJackson2HttpMessageConverter class in SpringMVC for decoding by default. Only when the status code is not 200 ~ Between 300, ErrorDecoder will be called. ErrorDecoder is used to return an exception based on the HTTP response information, which can be captured at the place where the Feign interface is called. Currently, we use ErrorDecoder to make the Feign interface throw a business exception for the caller to handle.

Feign HTTP Client

By default, Feign uses JDK's native URLConnection to send HTTP requests without a connection pool. However, it maintains a persistent connection for each address, that is, HTTP persistence connection. We can use Apache's HTTP Client to replace Feign's original http client, so as to obtain the connection pool, timeout, and other performance-related control capabilities. Spring Cloud supports this replacement from Brixtion. SR5. First, declare Apache HTTP Client andfeign-httpclientDependency:

<! -- Use Apache HttpClient to replace Feign native httpclient --> <dependency> <groupId> org. apache. httpcomponents </groupId> <artifactId> httpclient </artifactId> </dependency> <groupId> com. netflix. feign </groupId> <artifactId> feign-httpclient </artifactId> <version >$ {feign-httpclient} </version> </dependency>

Then add the following in application. properties:

feign.httpclient.enabled=true

Summary

Through Feign, we can make HTTP remote calls completely transparent to developers and get the same encoding experience as calling local methods. This is similar to exposing remote services in Alibaba Dubbo. The difference is that Dubbo is based on private binary protocol, while Feign is essentially an HTTP client. If you are using Spring Cloud Netflix to build microservices, Feign is undoubtedly the best choice.

The above section describes how to use Spring Cloud Feign as an HTTP client to call remote HTTP Services (recommended). I hope it will be helpful to you, if you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.