<title>1. Declarative REST Client: Feign</title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.79.1"><linkrel="home"href="multi_spring-cloud-openfeign.html"title="Spring Cloud OpenFeign"><linkrel="up"href="multi_spring-cloud-openfeign.html"title="Spring Cloud OpenFeign"><linkrel="prev"href="multi_pr01.html"title=""></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center">1. Declarative REST Client: Feign</th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi_pr01.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> </td></tr></table><hr></div><divclass="chapter"><divclass="titlepage"><div><div><h1class="title"><aname="spring-cloud-feign"href="#spring-cloud-feign"></a>1. Declarative REST Client: Feign</h1></div></div></div><p><aclass="link"href="https://github.com/Netflix/feign"target="_top">Feign</a> is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same <codeclass="literal">HttpMessageConverters</code> used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.</p><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="netflix-feign-starter"href="#netflix-feign-starter"></a>1.1 How to Include Feign</h2></div></div></div><p>To include Feign in your project use the starter with group <codeclass="literal">org.springframework.cloud</code>
and artifact id <codeclass="literal">spring-cloud-starter-openfeign</code>. See the <aclass="link"href="http://projects.spring.io/spring-cloud/"target="_top">Spring Cloud Project page</a>
for details on setting up your build system with the current Spring Cloud Release Train.</p><p>Example spring boot app</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@SpringBootApplication</span></em>
<em><spanclass="hl-annotation"style="color: gray">@RequestMapping(method = RequestMethod.GET, value = "/stores")</span></em>
List<Store> getStores();
<em><spanclass="hl-annotation"style="color: gray">@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")</span></em>
Store update(<em><spanclass="hl-annotation"style="color: gray">@PathVariable("storeId")</span></em> Long storeId, Store store);
}</pre><p>
</p><p>In the <codeclass="literal">@FeignClient</code> annotation the String value ("stores" above) is
an arbitrary client name, which is used to create a Ribbon load
balancer (see <aclass="link"href="">below for details of Ribbon
support</a>). You can also specify a URL using the <codeclass="literal">url</code> attribute
(absolute value or just a hostname). The name of the bean in the
application context is the fully qualified name of the interface.
To specify your own alias value you can use the <codeclass="literal">qualifier</code> value
of the <codeclass="literal">@FeignClient</code> annotation.</p><p>The Ribbon client above will want to discover the physical addresses
for the "stores" service. If your application is a Eureka client then
it will resolve the service in the Eureka service registry. If you
don’t want to use Eureka, you can simply configure a list of servers
in your external configuration (see
<aclass="link"href="">above for example</a>).</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="spring-cloud-feign-overriding-defaults"href="#spring-cloud-feign-overriding-defaults"></a>1.2 Overriding Feign Defaults</h2></div></div></div><p>A central concept in Spring Cloud’s Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the <codeclass="literal">@FeignClient</code> annotation. Spring Cloud creates a new ensemble as an
<codeclass="literal">ApplicationContext</code> on demand for each named client using <codeclass="literal">FeignClientsConfiguration</code>. This contains (amongst other things) an <codeclass="literal">feign.Decoder</code>, a <codeclass="literal">feign.Encoder</code>, and a <codeclass="literal">feign.Contract</code>.
It is possible to override the name of that ensemble by using the <codeclass="literal">contextId</code>
attribute of the <codeclass="literal">@FeignClient</code> annotation.</p><p>Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the <codeclass="literal">FeignClientsConfiguration</code>) using <codeclass="literal">@FeignClient</code>. Example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(name = "stores", configuration = FooConfiguration.class)</span></em>
}</pre><p>In this case the client is composed from the components already in <codeclass="literal">FeignClientsConfiguration</code> together with any in <codeclass="literal">FooConfiguration</code> (where the latter will override the former).</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">FooConfiguration</code> does not need to be annotated with <codeclass="literal">@Configuration</code>. However, if it is, then take care to exclude it from any <codeclass="literal">@ComponentScan</code> that would otherwise include this configuration as it will become the default source for <codeclass="literal">feign.Decoder</code>, <codeclass="literal">feign.Encoder</code>, <codeclass="literal">feign.Contract</code>, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any <codeclass="literal">@ComponentScan</code> or <codeclass="literal">@SpringBootApplication</code>, or it can be explicitly excluded in <codeclass="literal">@ComponentScan</code>.</p></td></tr></table></div><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>The <codeclass="literal">serviceId</code> attribute is now deprecated in favor of the <codeclass="literal">name</code> attribute.</p></td></tr></table></div><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>Using <codeclass="literal">contextId</code> attribute of the <codeclass="literal">@FeignClient</code> annotation in addition to changing the name of
the <codeclass="literal">ApplicationContext</code> ensemble, it will override the alias of the client name
and it will be used as part of the name of the configuration bean created for that client.</p></td></tr></table></div><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>Previously, using the <codeclass="literal">url</code> attribute, did not require the <codeclass="literal">name</code> attribute. Using <codeclass="literal">name</code> is now required.</p></td></tr></table></div><p>Placeholders are supported in the <codeclass="literal">name</code> and <codeclass="literal">url</code> attributes.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(name = "${feign.name}", url = "${feign.url}")</span></em>
}</pre><p>Spring Cloud Netflix provides the following beans by default for feign (<codeclass="literal">BeanType</code> beanName: <codeclass="literal">ClassName</code>):</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><codeclass="literal">Decoder</code> feignDecoder: <codeclass="literal">ResponseEntityDecoder</code> (which wraps a <codeclass="literal">SpringDecoder</code>)</li><liclass="listitem"><codeclass="literal">Encoder</code> feignEncoder: <codeclass="literal">SpringEncoder</code></li><liclass="listitem"><codeclass="literal">Logger</code> feignLogger: <codeclass="literal">Slf4jLogger</code></li><liclass="listitem"><codeclass="literal">Contract</code> feignContract: <codeclass="literal">SpringMvcContract</code></li><liclass="listitem"><codeclass="literal">Feign.Builder</code> feignBuilder: <codeclass="literal">HystrixFeign.Builder</code></li><liclass="listitem"><codeclass="literal">Client</code> feignClient: if Ribbon is enabled it is a <codeclass="literal">LoadBalancerFeignClient</code>, otherwise the default feign client is used.</li></ul></div><p>The OkHttpClient and ApacheHttpClient feign clients can be used by setting <codeclass="literal">feign.okhttp.enabled</code> or <codeclass="literal">feign.httpclient.enabled</code> to <codeclass="literal">true</code>, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either <codeclass="literal">ClosableHttpClient</code> when using Apache or <codeclass="literal">OkHttpClient</code> when using OK HTTP.</p><p>Spring Cloud Netflix <spanclass="emphasis"><em>does not</em></span> provide the following beans by default for feign, but still looks up beans of these types from the application context to create the feign client:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><codeclass="literal">Logger.Level</code></li><liclass="listitem"><codeclass="literal">Retryer</code></li><liclass="listitem"><codeclass="literal">ErrorDecoder</code></li><liclass="listitem"><codeclass="literal">Request.Options</code></li><liclass="listitem"><codeclass="literal">Collection<RequestInterceptor></code></li><liclass="listitem"><codeclass="literal">SetterFactory</code></li></ul></div><p>Creating a bean of one of those type and placing it in a <codeclass="literal">@FeignClient</code> configuration (such as <codeclass="literal">FooConfiguration</code> above) allows you to override each one of the beans described. Example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre><p>This replaces the <codeclass="literal">SpringMvcContract</code> with <codeclass="literal">feign.Contract.Default</code> and adds a <codeclass="literal">RequestInterceptor</code> to the collection of <codeclass="literal">RequestInterceptor</code>.</p><p><codeclass="literal">@FeignClient</code> also can be configured using configuration properties.</p><p>application.yml</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-attribute">feign</span>:
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-attribute"> contract</span>: com.example.SimpleContract</pre><p>Default configurations can be specified in the <codeclass="literal">@EnableFeignClients</code> attribute <codeclass="literal">defaultConfiguration</code> in a similar manner as described above. The difference is that this configuration will apply to <spanclass="emphasis"><em>all</em></span> feign clients.</p><p>If you prefer using configuration properties to configured all <codeclass="literal">@FeignClient</code>, you can create configuration properties with <codeclass="literal">default</code> feign name.</p><p>application.yml</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-attribute">feign</span>:
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-attribute"> loggerLevel</span>: basic</pre><p>If we create both <codeclass="literal">@Configuration</code> bean and configuration properties, configuration properties will win.
It will override <codeclass="literal">@Configuration</code> values. But if you want to change the priority to <codeclass="literal">@Configuration</code>,
you can change <codeclass="literal">feign.client.default-to-properties</code> to <codeclass="literal">false</code>.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>If you need to use <codeclass="literal">ThreadLocal</code> bound variables in your <codeclass="literal">RequestInterceptor`s you will need to either set the
thread isolation strategy for Hystrix to `SEMAPHORE</code> or disable Hystrix in Feign.</p></td></tr></table></div><p>application.yml</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-comment"># To disable Hystrix in Feign</span>
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-attribute"> strategy</span>: SEMAPHORE</pre><p>If we want to create multiple feign clients with the same name or url
so that they would point to the same server but each with a different custom configuration then
we have to use <codeclass="literal">contextId</code> attribute of the <codeclass="literal">@FeignClient</code> in order to avoid name
collision of these configuration beans.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class)</span></em>
}</pre></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_creating_feign_clients_manually"href="#_creating_feign_clients_manually"></a>1.3 Creating Feign Clients Manually</h2></div></div></div><p>In some cases it might be necessary to customize your Feign Clients in a way that is not
possible using the methods above. In this case you can create Clients using the
<aclass="link"href="https://github.com/OpenFeign/feign/#basics"target="_top">Feign Builder API</a>. Below is an example
which creates two Feign Clients with the same interface but configures each one with
a separate request interceptor.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Import(FeignClientsConfiguration.class)</span></em>
}</pre><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>In the above example <codeclass="literal">FeignClientsConfiguration.class</code> is the default configuration
provided by Spring Cloud Netflix.</p></td></tr></table></div><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">PROD-SVC</code> is the name of the service the Clients will be making requests to.</p></td></tr></table></div><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>The Feign <codeclass="literal">Contract</code> object defines what annotations and values are valid on interfaces. The
autowired <codeclass="literal">Contract</code> bean provides supports for SpringMVC annotations, instead of
the default Feign native annotations.</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="spring-cloud-feign-hystrix"href="#spring-cloud-feign-hystrix"></a>1.4 Feign Hystrix Support</h2></div></div></div><p>If Hystrix is on the classpath and <codeclass="literal">feign.hystrix.enabled=true</code>, Feign will wrap all methods with a circuit breaker. Returning a <codeclass="literal">com.netflix.hystrix.HystrixCommand</code> is also available. This lets you use reactive patterns (with a call to <codeclass="literal">.toObservable()</code> or <codeclass="literal">.observe()</code> or asynchronous use (with a call to <codeclass="literal">.queue()</code>).</p><p>To disable Hystrix support on a per-client basis create a vanilla <codeclass="literal">Feign.Builder</code> with the "prototype" scope, e.g.:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>Prior to the Spring Cloud Dalston release, if Hystrix was on the classpath Feign would have wrapped
all methods in a circuit breaker by default. This default behavior was changed in Spring Cloud Dalston in
favor for an opt-in approach.</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="spring-cloud-feign-hystrix-fallback"href="#spring-cloud-feign-hystrix-fallback"></a>1.5 Feign Hystrix Fallbacks</h2></div></div></div><p>Hystrix supports the notion of a fallback: a default code path that is executed when they circuit is open or there is an error. To enable fallbacks for a given <codeclass="literal">@FeignClient</code> set the <codeclass="literal">fallback</code> attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(name = "hello", fallback = HystrixClientFallback.class)</span></em>
}</pre><p>If one needs access to the cause that made the fallback trigger, one can use the <codeclass="literal">fallbackFactory</code> attribute inside <codeclass="literal">@FeignClient</code>.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)</span></em>
}</pre><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>There is a limitation with the implementation of fallbacks in Feign and how Hystrix fallbacks work. Fallbacks are currently not supported for methods that return <codeclass="literal">com.netflix.hystrix.HystrixCommand</code> and <codeclass="literal">rx.Observable</code>.</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_feign_and_primary"href="#_feign_and_primary"></a>1.6 Feign and <codeclass="literal">@Primary</code></h2></div></div></div><p>When using Feign with Hystrix fallbacks, there are multiple beans in the <codeclass="literal">ApplicationContext</code> of the same type. This will cause <codeclass="literal">@Autowired</code> to not work because there isn’t exactly one bean, or one marked as primary. To work around this, Spring Cloud Netflix marks all Feign instances as <codeclass="literal">@Primary</code>, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the <codeclass="literal">primary</code> attribute of <codeclass="literal">@FeignClient</code> to false.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient(name = "hello", primary = false)</span></em>
<em><spanclass="hl-annotation"style="color: gray">@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")</span></em>
User getUser(<em><spanclass="hl-annotation"style="color: gray">@PathVariable("id")</span></em><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-keyword">long</span> id);
</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>It is generally not advisable to share an interface between a
server and a client. It introduces tight coupling, and also actually
doesn’t work with Spring MVC in its current form (method parameter
mapping is not inherited).</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_feign_requestresponse_compression"href="#_feign_requestresponse_compression"></a>1.8 Feign request/response compression</h2></div></div></div><p>You may consider enabling the request or response GZIP compression for your
Feign requests. You can do this by enabling one of the properties:</p><preclass="programlisting">feign.compression.request.enabled=true
feign.compression.response.enabled=true</pre><p>Feign request compression gives you settings similar to what you may set for your web server:</p><preclass="programlisting">feign.compression.request.enabled=true
feign.compression.request.min-request-size=<spanclass="hl-number">2048</span></pre><p>These properties allow you to be selective about the compressed media types and minimum request threshold length.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_feign_logging"href="#_feign_logging"></a>1.9 Feign logging</h2></div></div></div><p>A logger is created for each Feign client created. By default the name of the logger is the full class name of the interface used to create the Feign client. Feign logging only responds to the <codeclass="literal">DEBUG</code> level.</p><p><b>application.yml. </b>
</p><p>The <codeclass="literal">Logger.Level</code> object that you may configure per client, tells Feign how much to log. Choices are:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><codeclass="literal">NONE</code>, No logging (<spanclass="strong"><strong>DEFAULT</strong></span>).</li><liclass="listitem"><codeclass="literal">BASIC</code>, Log only the request method and URL and the response status code and execution time.</li><liclass="listitem"><codeclass="literal">HEADERS</code>, Log the basic information along with request and response headers.</li><liclass="listitem"><codeclass="literal">FULL</code>, Log the headers, body, and metadata for both requests and responses.</li></ul></div><p>For example, the following would set the <codeclass="literal">Logger.Level</code> to <codeclass="literal">FULL</code>:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_feign_querymap_support"href="#_feign_querymap_support"></a>1.10 Feign @QueryMap support</h2></div></div></div><p>The OpenFeign <codeclass="literal">@QueryMap</code> annotation provides support for POJOs to be used as
GET parameter maps. Unfortunately, the default OpenFeign QueryMap annotation is
incompatible with Spring because it lacks a <codeclass="literal">value</code> property.</p><p>Spring Cloud OpenFeign provides an equivalent <codeclass="literal">@SpringQueryMap</code> annotation, which
is used to annotate a POJO or Map parameter as a query parameter map.</p><p>For example, the <codeclass="literal">Params</code> class defines parameters <codeclass="literal">param1</code> and <codeclass="literal">param2</code>:</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-comment">// Params.java</span>
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-comment">// [Getters and setters omitted for brevity]</span>
}</pre><p>The following feign client uses the <codeclass="literal">Params</code> class by using the <codeclass="literal">@SpringQueryMap</code> annotation:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@FeignClient("demo")</span></em>