Spring cloud feign using HTTP to request remote services

Source: Internet
Author: User

I. Introduction of feign

In the spring Cloud Netflix stack, each microservices exposes itself in the form of an HTTP interface, so the HTTP client must be used when invoking a remote service. We can use the JDK native URLConnection, Apache HTTP client, Netty asynchronous HTTP client, Spring resttemplate. However, the most convenient, the most elegant is to belong to the feign.

Feign is a declarative, templated HTTP client. Using feign in spring cloud, we can use HTTP to request a remote service with the same coding experience as a local method, and the developer is completely unaware that this is a remote method and is less aware that it is an HTTP request.

Ii. use of feign in spring cloud

1. Add dependencies

      <dependency >            < groupId >org.springframework.cloud</groupId>            <  Artifactid>spring-cloud-starter-feign</artifactid>       </dependency>

2. Create Feignclient

 @FeignClient (name= "spring-producer-server/spring"  public  interface   feignuserclient {@RequestMapping (value  = "/findall/{name}", Method = Requestmethod.get)  public  list<springuser>    FindAll (@PathVariable ("name"  = "/finduserpost", Method = Requestmethod.post) . Span style= "COLOR: #0000ff" >public   Springuser Finduserpost (@RequestBody Springuser springuser);//The composite type appears to be a POST request by default}  
    • @FeignClient (name= "spring-producer-server/spring"): Used to notify the feign component to proxy the interface (no need to write an interface implementation), the Name property specifies which service we want to invoke. Users can inject directly through @autowired.
    • @RequestMapping indicates that a GET request needs to be sent to/group/{groupid} when the method is called.
    • @PathVariable is the same as the corresponding annotation in SPRINGMVC.

Principle: When the Spring Cloud application starts, feign scans the interface labeled @feignclient Annotations, generates the agent, and registers it with the spring container. When the agent is generated, feign creates an Requettemplate object for each interface method that encapsulates all the information required by the HTTP request, the request parameter name, the request method, and so on, which are identified in the process, and feign's templating is here.

3. Add annotations on the startup class

@Configuration @componentscan@enableautoconfiguration@enableeurekaclient@enablefeignclients  Public class springconsumerserverfeignapplication {    publicstaticvoid  Main (string[ ] args) {        springapplication.run (springconsumerserverfeignapplication. class , args);}    }

4. configuration file Application.yml

spring:application:  name:spring-consumer-server-feignserver:  8084 Context- Path:/spring# The configuration content of the service registry, specifying the location of the service registry eureka:client:  serviceurl:   defaultzone:http:// User:[email protected]:8761/eureka/
iii. configuration of custom feign

1. Custom Configuration

@Configuration  Public class fooconfiguration {    @Bean    public  contract feigncontract () {        //  This replaces the SPRINGMVC contract with the feign. Contract.default        returnnew  feign. Contract.default ();    }}

2. Using a custom configuration

 @FeignClient (name= "spring-producer-server/spring", Configuration=fooconfiguration. Class  )  public  interface   feignuserclient {@RequestLine ( "Get/findall/{name}" )  public  list<springuser> findAll (@     Param ("name"  /*   @RequestMapping (value = "/findall/{    Name} ", method = requestmethod.get) public list<springuser> findAll (@PathVariable (" name ") String name); @RequestMapping (value = "/finduserpost", method = requestmethod.post) public Springuser finduserpost (@RequestBody Springuser springuser);  */ }  
@RequestLine: It's feign's note.

Iv. Configuration of feign logs
Create a logger for each feign client that you create. By default, the name of the logger is the full class name of the interface used to create the feign client. Feign log records respond only to the debug level. Logging.level.project.user.UserClient:DEBUG
In the configuration file application.yml, add:
Logging:level:  

To add a log level to a custom configuration class

@Configuration  Public class fooconfiguration {   /*  @Bean public    Contract feigncontract () {        //this will SPRINGMVC Contract is replaced with feign. Contract.default        return new feign. Contract.default ();    } */     @Bean    logger.level feignloggerlevel () {        // set log        return  Logger.Level.FULL;}    }

Ps:feign Request Timeout Issue

Hystrix the default time-out is 1 seconds, and if the time is not yet responding, it will enter the fallback code. The first request tends to be slow (because spring's lazy loading mechanism, to instantiate some classes), this response time may be more than 1 seconds
There are three solutions, taking feign as an example.
Method One
hystrix.command.default.execution.isolation.thread.timeoutinmilliseconds:5000
The configuration is to change the Hystrix timeout to 5 seconds
Method Two
Hystrix.command.default.execution.timeout.enabled:false
This configuration, which disables the timeout period for Hystrix
Method Three
Feign.hystrix.enabled:false
This configuration is used to simply disable the feign hystrix. This practice is not recommended unless some special scenarios are used.



Spring cloud feign using HTTP to request remote services

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.