Feign:web Service Client (translated)

Source: Internet
Author: User
Tags inheritance static class
declarative REST client:feign

Feign is a declarative Web service client. It makes Web service easier. With feign you just need to create an interface and write annotations. It provides pluggable feign annotations and jax-rs annotation support. The feign also provides a plug-and-pull codec. Spring Cloud adds annotation support for spring MVC and uses the same httpmessageconverters by default in the Spring Web. The spring cloud integrates ribbon and Eureka to provide load balancing. How to include feign

Org.springframework.cloud and Artifact ID spring-cloud-starter-feign. Spring Cloud Project page.

Example Spring Boot app:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients Public
class Application {public

    Stati void Main (string[] args) {
        Springapplication.run ( Application.class,args);
    }

Storeclient.java

@FeignClient ("sotes") public
interface storeclient{
    @RequestMapping (method=requestmethod.get,value= "/ Stores ")
    list<store> getstores ();

    @RequestMapping (method=requestmethod.post,value= "/stores/{storeid}", consumes= "Appliation/json")
    Store Update (@PathVariable ("StoreId") Long storeid,store Store);

In the @feignclient annotation is the name of an arbitrary service end (such as "store"), which is used to create a ribbon load balance. You can also specify a URL by using the URL attribute (absolute value or just a hostname). The name of the bean in the application context is the fully qualified name of the interface. An alias is also created by attaching "feignclient" on the "name" attribute. Look at the above, @Qualifire ("Storesfeignclient") can be used to reference the bean, if you want to change the default @qualifier value, this can be used @feignclient qualifier value.

Ribbon client will find the physical address of the "stores" service. If your application is Eureka client then eureka the registry will decide the service address. If you don't want to use Eureka, you can simply configure a server list in your external configuration. overriding feign Defaults

A core concept supported by Sping Cloud feign is the declared client. Each feign client is a part of the whole together through a remote server contact, use the @feignclient annotation to specify a whole name for use. Sping Cloud creates a new applictioncontxt for each client that uses the Feignclientconfiguration declaration. This includes (excluding other things) feign. Decode,feign. Encoder and Feign.contract.

Spring Cloud provides you with complete control of feign client by adding additional configuration to the @feignclient. For example:

@FeignClient (name= "stores", Configuration=fooconfiguration.class) public
interface storeclient{
}

In this example, the feignclientsconfiguration already has a client (the latter will overwrite the first) with the Fooconfiguration customization.

Warning: fooconfiguration must be @configuration, but note cannot be in @compinentscan, otherwise it will be used for each @feignclient. If you use @componentscan (or @ springbootapplication), you need to take some steps to avoid it (such as placing it in a separate, non-overlapping package, or specifying that the package is explicitly scanned in @componentscan).

Note: This serviceid is obsolete and recommends the use of the Name property

Warning: Previously, using the URL property, name is not required, but is now required.

Placeholders are supported for both the name and URL properties.

@FeignClient (name= "${feign,name}", Url= "${feign.url}") Public
interface storeclient{
}

Spring Cloud Netflix defaults to feign with the following beans (Beantype beanname:classname)
* Decoder Feigndecoder:respinseentitydecoder (packed with Springdeccoder)
* Encoder Fergnencoder:springencoder
* Logger Feignlogger:slf4jlogger
* Contract Feigncontract:springmvccontract
* Feign.builder FeignBuilder:HystrixFeign.Builder
* Client feignclient: If ribbon available is loadbalancerfeignclient, otherwise the default feign client.

Okhttpclient and Apachehttpclient feign clients can be set individually by fiegn.okhttp.enable or Feign.httpclient.enable is true and is added to Classpath.

Spring Cloud Netflix does not provide a bean by default, but you can still find these beans from the context and create the feign client:
* Logger.level
* Retryer
* Errordecoder
* Request.options
* Collection

Creating one of these types of beans can be placed in a @feignclient configuration (such as fooconfiguration), allowing you to overwrite each bean described. Example:

@Configuration public
class fooconfiguration{
    @Bean public
    Contract feigncontract () {return
        new Feign. Contract.default ();        
    }
    @Bean public
    basicauthrequestinterceptor Basicauthrequestinterceptor () {return
        new Basicauthrequestinterceptor ("User", "password");
    }

You can replace Springmvccontract and feign. Contract.default, and add a requestinterceptor to the requestinterceptor.

Can be specified in the same way through the @enablefeignclients property defaultconfiguration. The difference is that the configuration is loaded into all feign clients. creating feign Clients manually

In some cases you may need to customize feign clients but you cannot use the above method. So you can create clients using the Feign Builder API. The following is an example of creating a client with two identical interfaces but with a separate interceptor configured.

@Import (feignclientsconfiguration.class)
class Foocontroller {

private fooclient fooclient;

Private Fooclient adminclient;

@Autowired public
Foocontroller (
        responseentitydecoder decoder, Springencoder encoder, client client) {
    This.fooclient = Feign.builder (). Client (client).
            Encoder (Encoder).
            Decoder (decoder)
            . Requestinterceptor (New Basicauthrequestinterceptor ("User", "user"))
            . Target (Fooclient.class, "http:// Prod-svc ");
    This.adminclient = Feign.builder (). Client (client).
            Encoder (Encoder).
            Decoder (decoder)
            . Requestinterceptor (New Basicauthrequestinterceptor ("admin", "admin"))
            . Target (Fooclient.class, "http:// Prod-svc ");
    }
}

Note: In this example, Feignclientsconfiguration.class is the default configuration provided by the spring Cloud Netflix.

Prod-svc is the name of the service we provide and will receive requests from the appropriate client. Feign Hystrix Support

If Hystrix is in Classpath, the default feign wrap all methods in a fuse. Returning a Com.netflix.hystrix.HystrixCommand is also available. This allows you to use passive mode (using either. toobservable () or. Observer ()) or an asynchronous call (. Queue ()).

To disable Hystrix support for feign, set the Feign.hystrix.enabled=false.

To disable Hystrix support on each client, create a feign.builder and set scope to "prototype", for example:

@Configuration public
class Fooconfiguration {
    @Bean
    @Scope ("prototype") public
    Feign.builder Feignbuilder () {return
        feign.builder ();
    }
}
Feign Hystrix fallbacks

Hystrix supports the concept of fallback: A default code will be executed when the breaker is opened or an error occurs. To enable fallback to set the fallback property for @feignclient to implement a fallback.

@FeignClient (name= "Hello", Fallback=hystrixclientfallback.class)
protected interface Hystrixclient {
    @ Requestmapping (method=requestmethod.get,value= "/hello")
    Hello Ifailsometimes ();
}

Static class Hystrixclientfallback implements hystrixclient{
    @Override public
    Hello ifailsometimes () {
        return new Hello ("fallback");
    }

If a request triggers a fallback, you can replace @feignclient with the Fallbackfactory property.

@FeignClient (name = "Hello", fallbackfactory = hystrixclientfallbackfactory.class)
protected interface hystrixclient {
    @RequestMapping (method = requestmethod.get, value = "/hello")
    Hello Ifailsometimes ();
}

@Component
Static class Hystrixclientfallbackfactory implements fallbackfactory

Warning: There is a limitation with the implementation of fallbacks in feign and how Hystrix fallbacks. Fallbacks are currently not supported for methods the return Com.netflix.hystrix.HystrixCommand and RX. Observable. Feign inheritance Support

Feign supports referencing APIs through a single inheritance interface, which allows the grouping of common operations into a convenient basic interface.

Userservice.java Public
interface UserService {

@RequestMapping (method = requestmethod.get, value = "/users/{ ID} ")
User GetUser (@PathVariable (" id ") long ID);

Userresource.java
@RestController Public
class Userresource implements UserService {

}

Userclient.java
package project.user;

@FeignClient ("Users") public
interface Userclient extends UserService {

}

Note: It is often undesirable to share an interface between a server and a client. It introduces tight coupling, and it doesn't actually work in spring MVC (method parameter mappings are not inherited). Feign Request/response Compression

You may consider enabling gzip compression on your feign request. You can enable it by setting the following:

Feign.compression.request.enabled=true
Feign.compression.response.enabled=true

The compression settings provided by feign are similar to the settings of your Web server:

Feign.compression.request.enabled=true
Feign.compression.request.mime-types=text/xml,application/xml, Application/json
feign.compression.request.min-request-size=2048

These properties allow you to select the Mime-type to compress and the minimum request length. Feign Logging

Each feign client creates a logger. The name of the default logger is the fully qualified name of the feign client. The feign log responds only to the DEBUG level.

Application.yml
Logging.level.project.user.UserClient:DEBUG

You can configure Logger.level objects for each client, telling feign how many logs to log, and options include:
* None, not record (DEFAULT).
* BASIC, only record the request mode and URL and the response status code and execution time.
* HEADERS, log the basic information with the request and response headers.
* Full, recording headers and bodies and metadata for requests and responses.

For example, the following setting makes Logger.level full.

@Configuration public
class Fooconfiguration {
    @Bean
    logger.level feignloggerlevel () {
        return Logger.Level.FULL
    }
}

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.