Support for using OpenFeign in Spring Cloud apps
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

429 lines
23 KiB

<?xml version="1.0" encoding="UTF-8"?>
<?asciidoc-toc?>
<?asciidoc-numbered?>
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en">
<info>
<title>Spring Cloud OpenFeign</title>
<date>2019-03-08</date>
</info>
<preface>
<title></title>
<simpara><emphasis role="strong">2.1.2.BUILD-SNAPSHOT</emphasis></simpara>
<simpara>This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration
and binding to the Spring Environment and other Spring programming model idioms.</simpara>
</preface>
<chapter xml:id="spring-cloud-feign">
<title>Declarative REST Client: Feign</title>
<simpara><link xl:href="https://github.com/Netflix/feign">Feign</link> 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 <literal>HttpMessageConverters</literal> used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.</simpara>
<section xml:id="netflix-feign-starter">
<title>How to Include Feign</title>
<simpara>To include Feign in your project use the starter with group <literal>org.springframework.cloud</literal>
and artifact id <literal>spring-cloud-starter-openfeign</literal>. See the <link xl:href="https://projects.spring.io/spring-cloud/">Spring Cloud Project page</link>
for details on setting up your build system with the current Spring Cloud Release Train.</simpara>
<simpara>Example spring boot app</simpara>
<programlisting language="java" linenumbering="unnumbered">@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}</programlisting>
<formalpara>
<title>StoreClient.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List&lt;Store&gt; getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}</programlisting>
</para>
</formalpara>
<simpara>In the <literal>@FeignClient</literal> annotation the String value ("stores" above) is
an arbitrary client name, which is used to create a Ribbon load
balancer (see <link linkend="spring-cloud-ribbon">below for details of Ribbon
support</link>). You can also specify a URL using the <literal>url</literal> 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 <literal>qualifier</literal> value
of the <literal>@FeignClient</literal> annotation.</simpara>
<simpara>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&#8217;t want to use Eureka, you can simply configure a list of servers
in your external configuration (see
<link linkend="spring-cloud-ribbon-without-eureka">above for example</link>).</simpara>
</section>
<section xml:id="spring-cloud-feign-overriding-defaults">
<title>Overriding Feign Defaults</title>
<simpara>A central concept in Spring Cloud&#8217;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 <literal>@FeignClient</literal> annotation. Spring Cloud creates a new ensemble as an
<literal>ApplicationContext</literal> on demand for each named client using <literal>FeignClientsConfiguration</literal>. This contains (amongst other things) an <literal>feign.Decoder</literal>, a <literal>feign.Encoder</literal>, and a <literal>feign.Contract</literal>.
It is possible to override the name of that ensemble by using the <literal>contextId</literal>
attribute of the <literal>@FeignClient</literal> annotation.</simpara>
<simpara>Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the <literal>FeignClientsConfiguration</literal>) using <literal>@FeignClient</literal>. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}</programlisting>
<simpara>In this case the client is composed from the components already in <literal>FeignClientsConfiguration</literal> together with any in <literal>FooConfiguration</literal> (where the latter will override the former).</simpara>
<note>
<simpara><literal>FooConfiguration</literal> does not need to be annotated with <literal>@Configuration</literal>. However, if it is, then take care to exclude it from any <literal>@ComponentScan</literal> that would otherwise include this configuration as it will become the default source for <literal>feign.Decoder</literal>, <literal>feign.Encoder</literal>, <literal>feign.Contract</literal>, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any <literal>@ComponentScan</literal> or <literal>@SpringBootApplication</literal>, or it can be explicitly excluded in <literal>@ComponentScan</literal>.</simpara>
</note>
<note>
<simpara>The <literal>serviceId</literal> attribute is now deprecated in favor of the <literal>name</literal> attribute.</simpara>
</note>
<note>
<simpara>Using <literal>contextId</literal> attribute of the <literal>@FeignClient</literal> annotation in addition to changing the name of
the <literal>ApplicationContext</literal> 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.</simpara>
</note>
<warning>
<simpara>Previously, using the <literal>url</literal> attribute, did not require the <literal>name</literal> attribute. Using <literal>name</literal> is now required.</simpara>
</warning>
<simpara>Placeholders are supported in the <literal>name</literal> and <literal>url</literal> attributes.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}</programlisting>
<simpara>Spring Cloud Netflix provides the following beans by default for feign (<literal>BeanType</literal> beanName: <literal>ClassName</literal>):</simpara>
<itemizedlist>
<listitem>
<simpara><literal>Decoder</literal> feignDecoder: <literal>ResponseEntityDecoder</literal> (which wraps a <literal>SpringDecoder</literal>)</simpara>
</listitem>
<listitem>
<simpara><literal>Encoder</literal> feignEncoder: <literal>SpringEncoder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Logger</literal> feignLogger: <literal>Slf4jLogger</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Contract</literal> feignContract: <literal>SpringMvcContract</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Feign.Builder</literal> feignBuilder: <literal>HystrixFeign.Builder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Client</literal> feignClient: if Ribbon is enabled it is a <literal>LoadBalancerFeignClient</literal>, otherwise the default feign client is used.</simpara>
</listitem>
</itemizedlist>
<simpara>The OkHttpClient and ApacheHttpClient feign clients can be used by setting <literal>feign.okhttp.enabled</literal> or <literal>feign.httpclient.enabled</literal> to <literal>true</literal>, respectively, and having them on the classpath.
You can customize the HTTP client used by providing a bean of either <literal>ClosableHttpClient</literal> when using Apache or <literal>OkHttpClient</literal> when using OK HTTP.</simpara>
<simpara>Spring Cloud Netflix <emphasis>does not</emphasis> 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:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>Logger.Level</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Retryer</literal></simpara>
</listitem>
<listitem>
<simpara><literal>ErrorDecoder</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Request.Options</literal></simpara>
</listitem>
<listitem>
<simpara><literal>Collection&lt;RequestInterceptor&gt;</literal></simpara>
</listitem>
<listitem>
<simpara><literal>SetterFactory</literal></simpara>
</listitem>
</itemizedlist>
<simpara>Creating a bean of one of those type and placing it in a <literal>@FeignClient</literal> configuration (such as <literal>FooConfiguration</literal> above) allows you to override each one of the beans described. Example:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}</programlisting>
<simpara>This replaces the <literal>SpringMvcContract</literal> with <literal>feign.Contract.Default</literal> and adds a <literal>RequestInterceptor</literal> to the collection of <literal>RequestInterceptor</literal>.</simpara>
<simpara><literal>@FeignClient</literal> also can be configured using configuration properties.</simpara>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered">feign:
client:
config:
feignName:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract</programlisting>
<simpara>Default configurations can be specified in the <literal>@EnableFeignClients</literal> attribute <literal>defaultConfiguration</literal> in a similar manner as described above. The difference is that this configuration will apply to <emphasis>all</emphasis> feign clients.</simpara>
<simpara>If you prefer using configuration properties to configured all <literal>@FeignClient</literal>, you can create configuration properties with <literal>default</literal> feign name.</simpara>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered">feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic</programlisting>
<simpara>If we create both <literal>@Configuration</literal> bean and configuration properties, configuration properties will win.
It will override <literal>@Configuration</literal> values. But if you want to change the priority to <literal>@Configuration</literal>,
you can change <literal>feign.client.default-to-properties</literal> to <literal>false</literal>.</simpara>
<note>
<simpara>If you need to use <literal>ThreadLocal</literal> bound variables in your <literal>RequestInterceptor`s you will need to either set the
thread isolation strategy for Hystrix to `SEMAPHORE</literal> or disable Hystrix in Feign.</simpara>
</note>
<simpara>application.yml</simpara>
<programlisting language="yaml" linenumbering="unnumbered"># To disable Hystrix in Feign
feign:
hystrix:
enabled: false
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE</programlisting>
<simpara>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 <literal>contextId</literal> attribute of the <literal>@FeignClient</literal> in order to avoid name
collision of these configuration beans.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class)
public interface FooClient {
//..
}</programlisting>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(contextId = "barClient", name = "stores", configuration = BarConfiguration.class)
public interface BarClient {
//..
}</programlisting>
</section>
<section xml:id="_creating_feign_clients_manually">
<title>Creating Feign Clients Manually</title>
<simpara>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
<link xl:href="https://github.com/OpenFeign/feign/#basics">Feign Builder API</link>. Below is an example
which creates two Feign Clients with the same interface but configures each one with
a separate request interceptor.</simpara>
<programlisting language="java" linenumbering="unnumbered">@Import(FeignClientsConfiguration.class)
class FooController {
private FooClient fooClient;
private FooClient adminClient;
@Autowired
public FooController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
this.fooClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "http://PROD-SVC");
this.adminClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "http://PROD-SVC");
}
}</programlisting>
<note>
<simpara>In the above example <literal>FeignClientsConfiguration.class</literal> is the default configuration
provided by Spring Cloud Netflix.</simpara>
</note>
<note>
<simpara><literal>PROD-SVC</literal> is the name of the service the Clients will be making requests to.</simpara>
</note>
<note>
<simpara>The Feign <literal>Contract</literal> object defines what annotations and values are valid on interfaces. The
autowired <literal>Contract</literal> bean provides supports for SpringMVC annotations, instead of
the default Feign native annotations.</simpara>
</note>
</section>
<section xml:id="spring-cloud-feign-hystrix">
<title>Feign Hystrix Support</title>
<simpara>If Hystrix is on the classpath and <literal>feign.hystrix.enabled=true</literal>, Feign will wrap all methods with a circuit breaker. Returning a <literal>com.netflix.hystrix.HystrixCommand</literal> is also available. This lets you use reactive patterns (with a call to <literal>.toObservable()</literal> or <literal>.observe()</literal> or asynchronous use (with a call to <literal>.queue()</literal>).</simpara>
<simpara>To disable Hystrix support on a per-client basis create a vanilla <literal>Feign.Builder</literal> with the "prototype" scope, e.g.:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}</programlisting>
<warning>
<simpara>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.</simpara>
</warning>
</section>
<section xml:id="spring-cloud-feign-hystrix-fallback">
<title>Feign Hystrix Fallbacks</title>
<simpara>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 <literal>@FeignClient</literal> set the <literal>fallback</literal> attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.</simpara>
<programlisting language="java" linenumbering="unnumbered">@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");
}
}</programlisting>
<simpara>If one needs access to the cause that made the fallback trigger, one can use the <literal>fallbackFactory</literal> attribute inside <literal>@FeignClient</literal>.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory&lt;HystrixClient&gt; {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClient() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}</programlisting>
<warning>
<simpara>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 <literal>com.netflix.hystrix.HystrixCommand</literal> and <literal>rx.Observable</literal>.</simpara>
</warning>
</section>
<section xml:id="_feign_and_primary">
<title>Feign and <literal>@Primary</literal></title>
<simpara>When using Feign with Hystrix fallbacks, there are multiple beans in the <literal>ApplicationContext</literal> of the same type. This will cause <literal>@Autowired</literal> to not work because there isn&#8217;t exactly one bean, or one marked as primary. To work around this, Spring Cloud Netflix marks all Feign instances as <literal>@Primary</literal>, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the <literal>primary</literal> attribute of <literal>@FeignClient</literal> to false.</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient(name = "hello", primary = false)
public interface HelloClient {
// methods here
}</programlisting>
</section>
<section xml:id="spring-cloud-feign-inheritance">
<title>Feign Inheritance Support</title>
<simpara>Feign supports boilerplate apis via single-inheritance interfaces.
This allows grouping common operations into convenient base interfaces.</simpara>
<formalpara>
<title>UserService.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">public interface UserService {
@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id);
}</programlisting>
</para>
</formalpara>
<formalpara>
<title>UserResource.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">@RestController
public class UserResource implements UserService {
}</programlisting>
</para>
</formalpara>
<formalpara>
<title>UserClient.java</title>
<para>
<programlisting language="java" linenumbering="unnumbered">package project.user;
@FeignClient("users")
public interface UserClient extends UserService {
}</programlisting>
</para>
</formalpara>
<note>
<simpara>It is generally not advisable to share an interface between a
server and a client. It introduces tight coupling, and also actually
doesn&#8217;t work with Spring MVC in its current form (method parameter
mapping is not inherited).</simpara>
</note>
</section>
<section xml:id="_feign_requestresponse_compression">
<title>Feign request/response compression</title>
<simpara>You may consider enabling the request or response GZIP compression for your
Feign requests. You can do this by enabling one of the properties:</simpara>
<programlisting language="java" linenumbering="unnumbered">feign.compression.request.enabled=true
feign.compression.response.enabled=true</programlisting>
<simpara>Feign request compression gives you settings similar to what you may set for your web server:</simpara>
<programlisting language="java" linenumbering="unnumbered">feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048</programlisting>
<simpara>These properties allow you to be selective about the compressed media types and minimum request threshold length.</simpara>
</section>
<section xml:id="_feign_logging">
<title>Feign logging</title>
<simpara>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 <literal>DEBUG</literal> level.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<programlisting language="yaml" linenumbering="unnumbered">logging.level.project.user.UserClient: DEBUG</programlisting>
</para>
</formalpara>
<simpara>The <literal>Logger.Level</literal> object that you may configure per client, tells Feign how much to log. Choices are:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>NONE</literal>, No logging (<emphasis role="strong">DEFAULT</emphasis>).</simpara>
</listitem>
<listitem>
<simpara><literal>BASIC</literal>, Log only the request method and URL and the response status code and execution time.</simpara>
</listitem>
<listitem>
<simpara><literal>HEADERS</literal>, Log the basic information along with request and response headers.</simpara>
</listitem>
<listitem>
<simpara><literal>FULL</literal>, Log the headers, body, and metadata for both requests and responses.</simpara>
</listitem>
</itemizedlist>
<simpara>For example, the following would set the <literal>Logger.Level</literal> to <literal>FULL</literal>:</simpara>
<programlisting language="java" linenumbering="unnumbered">@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}</programlisting>
</section>
<section xml:id="_feign_querymap_support">
<title>Feign @QueryMap support</title>
<simpara>The OpenFeign <literal>@QueryMap</literal> 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 <literal>value</literal> property.</simpara>
<simpara>Spring Cloud OpenFeign provides an equivalent <literal>@SpringQueryMap</literal> annotation, which
is used to annotate a POJO or Map parameter as a query parameter map.</simpara>
<simpara>For example, the <literal>Params</literal> class defines parameters <literal>param1</literal> and <literal>param2</literal>:</simpara>
<programlisting language="java" linenumbering="unnumbered">// Params.java
public class Params {
private String param1;
private String param2;
// [Getters and setters omitted for brevity]
}</programlisting>
<simpara>The following feign client uses the <literal>Params</literal> class by using the <literal>@SpringQueryMap</literal> annotation:</simpara>
<programlisting language="java" linenumbering="unnumbered">@FeignClient("demo")
public class DemoTemplate {
@GetMapping(path = "/demo")
String demoEndpoint(@SpringQueryMap Params params);
}</programlisting>
</section>
</chapter>
</book>