Spring Cloud官方文档中文版-声明式Rest客户端:Feign

官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign

文中例子我做了一些测试在:http://git.oschina.net/dreamingodd/spring-cloud-preparation

Declarative REST Client: Feign 声明式Rest客户端:Feign

Feign 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 HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.

Feigh是一个声明式web服务客户端。它能让开发web服务变得容易。使用Feign需要创建一个接口并注解它。它拥有包括Feign注解和JAX-RS注解的可插拔支持。它还支持可插拔的编码器和解码器。Spring Cloud拥有Spring MVC支持,并使用Spring Web中默认同样的HttpMessageConverters。在使用Feign时,Spring Cloud集成了Ribbon和Eureka来提供负载均衡的HTTP客户端。

How to Include Feign

To include Feign in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-feign. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

org.springframework.cloud spring-cloud-starter-feign 更多详细内容请移步Spring Cloud Project

Example spring boot app

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

StoreClient.java

@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
}

In the @FeignClient annotation the String value ("stores" above) is an arbitrary client name, which is used to create a Ribbon load balancer (see below for details of Ribbon support). You can also specify a URL 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. To specify your own alias value you can use the qualifier value of the @FeignClient annotation.

@FeignClient注解中的String(也就是上面的“stores”)可以是任意的客户端名称,用于创建Ribbon负载均衡器(详见上文Ribbon supprot)。开发人员亦可使用URL(绝对路径或主机名)。application上下文中的bean名称为该接口的全限定名称。要制定别名的话,开发人员可以用@FeignClient注解的限定名称。

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 above for example).

上文中的Ribbon客户端会尝试发现“stores”服务的物理地址。如果它是一个Eureka客户端,那么服务就会再Eureka服务注册机中注册。如果不想使用Eureka,开发人员可以在外部配置中简单配置服务列表。(参见上文)

Overriding Feign Defaults 覆盖Feign默认行为

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 @FeignClient annotation. Spring Cloud creates a new ensemble as an ApplicationContext on demand for each named client using FeignClientsConfiguration. This contains (amongst other things) an feign.Decoder, a feign.Encoder, and a feign.Contract.

Spring Cloud的Feign支持的核心概念(之一)是命名客户端。每个Feign客户端都是组件集合的一部分,它们按需共同工作去链接远程服务器,该集合的名称由开发人员定义在@FeignClient注解中。Spring Cloud为每个使用FeignClientConfiguration的命名客户端按需创建ApplicationContext-组件集合。集合包括feign.Decoder,feign.Encoder和feign.Contract。

Spring Cloud lets you take full control of the feign client by declaring additional configuration (on top of the FeignClientsConfiguration) using @FeignClient. Example:

与使用Ribbon时一样,声明额外的configuration可以让Spring Cloud把全部控制权交给开发人员。例如:

@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}

In this case the client is composed from the components already in FeignClientsConfiguration together with any in FooConfiguration (where the latter will override the former).

本例中,客户端由已在FeignClientsConfiguration中的组件以及FooConfiguration中的任意组件组成(后者通常覆盖前者)。

NOTE FooConfiguration does not need to be annotated with @Configuration. However, if it is, then take care to exclude it from any @ComponentScan that would otherwise include this configuration as it will become the default source for feign.Decoder, feign.Encoder, feign.Contract, etc., when specified. This can be avoided by putting it in a separate, non-overlapping package from any @ComponentScan or @SpringBootApplication, or it can be explicitly excluded in @ComponentScan.

注意 FooConfiguration必须有@Configuration,但注意它并不在主应用上下文的@ComponentScan中,否则它会被所有的@RibbonClients分享(意思就是覆盖所有客户端的默认值)。如果开发人员使用@ComponentScan(或@SpringBootApplication),那就必须采取措施避免被覆盖到(例如将其放入一个独立的,不重叠的包中,或以@ComponentScan指明要扫描的包。

NOTE The serviceId attribute is now deprecated in favor of the name attribute.

注意 ServiceId属性现已启用,更多使用name属性。

WARNING Previously, using the url attribute, did not require the name attribute. Using name is now required.

警告 之前使用URL属性不需要name属性。但现在需要了。

Placeholders are supported in the name and url attributes.

Name和URL属性支持占位符。比如:

@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}

Spring Cloud Netflix provides the following beans by default for feign (BeanType beanName: ClassName):

Spring Cloud Netflix为feign提供以下默认bean(Bean类型 bean名称: Class名称):

  • Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)
  • Encoder feignEncoder: SpringEncoder
  • Logger feignLogger: Slf4jLogger
  • Contract feignContract: SpringMvcContract
  • Feign.Builder feignBuilder: HystrixFeign.Builder
  • Client feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used.

The OkHttpClient and ApacheHttpClient feign clients can be used by setting feign.okhttp.enabled or feign.httpclient.enabled to true, respectively, and having them on the classpath.

要使用OkHttpClient或ApacheHttpClient,需要把feign.okhttp.enabled或feign.httpclient.enabled设置为true并将其放入classpath。

Spring Cloud Netflix does not 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:

Spring Cloud Netflix并不默认提供以下bean,但是创建Feign客户端时,仍然会去application上下文中寻找这些类型的bean。

  • Logger.Level
  • Retryer
  • ErrorDecoder
  • Request.Options
  • Collection<RequestInterceptor>
  • SetterFactory

Creating a bean of one of those type and placing it in a @FeignClient configuration (such as FooConfiguration above) allows you to override each one of the beans described. Example:

覆盖上文的bean只需创建并将其放入@FeignClient配置类中(比如上文的FooConfiguration)。实例:

@Configuration
public class FooConfiguration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}

This replaces the SpringMvcContract with feign.Contract.Default and adds a RequestInterceptor to the collection of RequestInterceptor.

以上代码用feign.Contract.Default替换了SpringMvcContract,并在RequestInterceptor集合中加入了一个新的。

Default configurations can be specified in the @EnableFeignClients attribute defaultConfiguration in a similar manner as described above. The difference is that this configuration will apply to all feign clients.

与上文描述类似,默认配置可以在@EnableFeignClients属性默认配置中指定。不同点在于这样做将会影响所有的feign客户端。

NOTE If you need to use ThreadLocal bound variables in your RequestInterceptor's you will need to either set the thread isolation strategy for Hystrix to "SEMAPHORE" or disable Hystrix in Feign.

注意 若开发人员需要在RequestInterceptor中使用ThreadLocal变量,则需要将Hystrix的隔离级别设置为“SEMAPHORE”,或直接禁用Hystrix。

application.yml

# To disable Hystrix in Feign
feign:
hystrix:
enabled: false
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE

Creating Feign Clients Manually 手动创建Feign客户端

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 Feign Builder API. Below is an example which creates two Feign Clients with the same interface but configures each one with a separate request interceptor.

特殊情况下,当上文中的方法不可用的时候,开发人员需要自定义Ribbon客户端,请参考Feign Builder API。下文是一个创建两个具有相同接口的Feign客户端,但配置使用不同拦截器的示例:

@Import(FeignClientsConfiguration.class)
class FooController {
private FooClient fooClient;
private FooClient adminClient;
@Autowired
public FooController(
Decoder decoder, Encoder 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 the above example FeignClientsConfiguration.class is the default configuration provided by Spring Cloud Netflix.

注意 上文中的FeignClientsConfiguration.class是Spring Cloud Netflix提供的默认配置。

NOTE PROD-SVC is the name of the service the Clients will be making requests to.

注意 PROD-SVC是客户端会去请求的服务名。

Feign Hystrix Support Feign的Hystrix支持

If Hystrix is on the classpath and feign.hystrix.enabled=true, Feign will wrap all methods with a circuit breaker. Returning a com.netflix.hystrix.HystrixCommand is also available. This lets you use reactive patterns (with a call to .toObservable() or .observe() or asynchronous use (with a call to .queue()).

如果Hystrix在classpath中并把feign.hystrix.enabled设置为true,那么Feign将用断路器包装所有的方法。返回com.netflix.hystrix.HystrixCommand也是可用的。这使开发人员能够使用反应模式(调用.toObservable()或.observe()或异步使用-调用.queue())

To disable Hystrix support on a per-client basis create a vanilla Feign.Builder with the "prototype" scope, e.g.:

禁用Hystrix支持,要创建有一个带有“原型”周期的vanilla Feign.Builder。 例如:

@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}

WARNING 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.

警告 在Dalston版本之前,Feign + Hystrix默认用断路器包装所有方法。Dalston版本改成了选择进入的方式

Feign Hystrix Fallbacks Feign Hystrix失败回退

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 @FeignClient set the fallback attribute to the class name that implements the fallback. You also need to declare your implementation as a Spring bean.

Hystrix支持失败回退理念:无论断路器成功还是失败都会一个默认的代码路径。开启fallback只需给@FeignClient加入fallback属性并实现fallback接口。开发人员同样需要声明实现为一个Spring的bean。

@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 one needs access to the cause that made the fallback trigger, one can use the fallbackFactory attribute inside @FeignClient.

如果需要访问导致失败回退触发的原因,可以使用@FeignClient中的fallbackFactory属性。

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello iFailSometimes();
}
@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
@Override
public HystrixClient create(Throwable cause) {
return new HystrixClientWithFallBackFactory() {
@Override
public Hello iFailSometimes() {
return new Hello("fallback; reason was: " + cause.getMessage());
}
};
}
}

WARNING 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 com.netflix.hystrix.HystrixCommand and rx.Observable.

警告 Feign的实现和Hystrix的失败回退方式有一个局限性。暂不支持返回com.netflix.hystrix.HystrixCommand and rx.Observable的方法。

Feign and @Primary

When using Feign with Hystrix fallbacks, there are multiple beans in the ApplicationContext of the same type. This will cause @Autowired 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 @Primary, so Spring Framework will know which bean to inject. In some cases, this may not be desirable. To turn off this behavior set the primary attribute of @FeignClient to false.

使用Hystrix fallbacks时,ApplicationContext中有相同类型的多个bean。导致@Autowired定位不到准确的bean,或标记为@Primary。解决这个问题,Spring Cloud Netflix将所有Feign实例标记为@Primary,这样Spring框架将会知道要注入哪个bean。在某些情况下,这可能是不可取的。 要关闭此行为,将@FeignClient的主属性设置为false。

@FeignClient(name = "hello", primary = false)
public interface HelloClient {
// methods here
}

Feign Inheritance Support Feign继承支持

Feign supports boilerplate apis via single-inheritance interfaces. This allows grouping common operations into convenient base interfaces.

Feign通过单继承接口支持样板文件API。好处是将公共操作分组到便利的基本接口中了。

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 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).

注意 一般不建议讲一个接口同时设置为服务端和客户端。这样就引入了紧耦合,并且实际上在当前模式下无法和Spring MVC协同工作(方法参数映射不被继承)。

Feign request/response compression Feign的请求/响应压缩

You may consider enabling the request or response GZIP compression for your Feign requests. You can do this by enabling one of the properties:

如果考虑压缩request/response为GZIP,使用以下属性:

feign.compression.request.enabled=true
feign.compression.response.enabled=true

Feign request compression gives you settings similar to what you may set for your web server:

Feign请求压缩有类似web服务器的配置:

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 be selective about the compressed media types and minimum request threshold length.

这些属性可以控制压缩的媒体类型和最小请求阈值。

Feign logging

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 DEBUG level.

application.yml

logging.level.project.user.UserClient: DEBUG

The Logger.Level object that you may configure per client, tells Feign how much to log. Choices are:

可以为每个客户端配置日志级别(Logger.Level),选项有:

  • NONE, No logging (DEFAULT).
  • BASIC, Log only the request method and URL and the response status code and execution time.
  • HEADERS, Log the basic information along with request and response headers.
  • FULL, Log the headers, body, and metadata for both requests and responses.

For example, the following would set the Logger.Level to FULL:

下例将日志级别设为全部(FULL):

@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
dreamingodd原创文章,如转载请注明出处。
 
上一篇:Python3 函数式编程自带函数


下一篇:一个NPOI导出到excel文件的范例记录