Feign简介
在Feign的官方文档上, 我们可以看到Feign最重要的一句话是:Feign makes writing java http clients easier。Feign主要的目也是为了简化我们编写远程访问的代码量。在使用 Feign 时, 可以使用注解来修饰接口, 这些注解中既包括了 Feign 自带的注解, 也支持使用第三方的注解(通过注解转换来实现)。 除此之外, Feign还支持插件式的编码器和解码器, 使用者可以通过该特性, 对请求和响应进行不同的封装与解析。Feign可以决定采用什么方式调用第三方接口OkHttpClient或者RibbonClient。而所有的这些特性都可以很容易的进行扩展,这也是Spring Cloud选择Feign的原因。官方文档:https://github.com/OpenFeign/feign
Feign简单实例
- 编写服务端的逻辑。可以通过Spring boot,提供任何一个接口供系统调用,如下便提供了一个简单的接口:
package com.ivan.provider.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ivan.provider.entity.User;
@RestController
public class UserController {
@RequestMapping(value="/user/{id}")
public User getUser(@PathVariable(value = "id") Integer id){
User user = new User();
user.setId(id);
user.setName("ivan chen");
user.setAge(18);
return user;
}
}
+在客户端需要引入feign相关的类,pom.xml代码如下:
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.7.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.7.0</version>
</dependency>
</dependencies>
- 在客户端首先定义一个接口,我们的代码可以通过这个接口调用直接拿到我们想要的数据,代码如下:
package com.ivan.feign.client.service;
import com.ivan.feign.client.entity.User;
import feign.Param;
import feign.RequestLine;
public interface UserService {
@RequestLine("GET /user/{id}")
public User getUser(@Param("id") Integer id);
}
- 编写客户端的调用逻辑,我们可以在代码里直接通过UserService这个接口得到数据,省去了通过构造一系列的http client对象。代码如下:
package com.ivan.feign.client;
import com.ivan.feign.client.entity.User;
import com.ivan.feign.client.service.UserService;
import feign.Feign;
import feign.gson.GsonDecoder;
public class Client {
public static void main(String[] args) {
// 可以通过UserService进行方法的调用了。
UserService userService = Feign.builder().decoder(new GsonDecoder()).target(UserService.class, "http://localhost:8000");
//直接就能够得到User对象,这样代码逻辑上就更面向对象了
User user = userService.getUser(2);
System.out.println(user.getName());
}
}
Feign的编解码器
通过上面的实例,可以看出通过Feign调用第三方接口会方便很多,除了不需要设置一系列的请求参数外,Feign还帮我们将请求返回的数据转成我们需要的业务对象,而这一切是通过解码器办到的。Feign还提供了编码器,他能够将我们需要发送的业务对象转成服务端能够接受的格式, 比如json格式,xml格式。
Feign编码器实例
- 服务端增加一个服务接口,接收json格式的数据,代码如下:
package com.ivan.provider.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ivan.provider.entity.User;
@RestController
public class UserController {
@RequestMapping(value = "/user/{id}")
public User getUser(@PathVariable(value = "id") Integer id) {
User user = new User();
user.setId(id);
user.setName("ivan chen");
user.setAge(18);
return user;
}
@RequestMapping(value = "/user/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public User createUserPerson(@RequestBody User user) {
System.out.println(user.getName());
user.setId(15);
return user;
}
}
- 客户端增加一个接口描述,这里面要用到Feign的 Headers注解,用于表明调用当前方法的时候,需要转成什么格式的数据,代码如下:
package com.ivan.feign.client.service;
import com.ivan.feign.client.entity.User;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
public interface UserService {
@RequestLine("GET /user/{id}")
public User getUser(@Param("id") Integer id);
@RequestLine("POST /user/create")
@Headers("Content-Type: application/json")
public User create(User user);
}
- 构造接口的实例对象的时候需要传入一个编码器对象,Feign对json格式提供了gson的编码器,我们可以利用这个编码器实现对象到json格式的转换。代码如下:
package com.ivan.feign.client;
import com.ivan.feign.client.entity.User;
import com.ivan.feign.client.service.UserService;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
public class Client {
public static void main(String[] args) {
/* // 可以通过UserService进行方法的调用了。
UserService userService = Feign.builder().decoder(new GsonDecoder()).target(UserService.class, "http://localhost:8000");
//直接就能够得到User对象,这样代码逻辑上就更面向对象了
User user = userService.getUser(2);
System.out.println(user.getName());*/
UserService userService = Feign.builder().encoder(new GsonEncoder()).decoder(new GsonDecoder()).target(UserService.class, "http://localhost:8000");
User user = new User();
user.setName("张山");
user.setAge(88);
user = userService.create(user);
System.out.println(user.getId());
}
}
Spring Cloud里应用Feign
- 首先需要在pom.xml文件里加上相关的依赖,pom.xml里的代码如下:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
spring-cloud-starter-feign 这个 JAR包包含了Ribbon相关的依赖,也就是说在实际开发中,只要集成了Feign,自动就集成了Ribbon。有相应的负载能力了。
- 定义消费端要用到的接口,这里用到的注解变成了Spring MVC提供的注解了,说明Spring Cloud在集成Feign的时候做了相应的注解转换。FeignClient里需要写上这个类是调用那个服务端的名称。
package com.ivan.client.feign.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ivan.client.feign.entity.User;
@FeignClient("provider")
public interface UserService {
@RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
public User getUser(@PathVariable("id") Integer id);
@RequestMapping(method = RequestMethod.POST, value = "/user/create", consumes = MediaType.APPLICATION_JSON_VALUE)
public User create(User user);
}
- 在启动类上加上EnableFeignClients注解。
package com.ivan.client.feign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
- 编写服务消费端,在服务消费端,可以直接通过Autowired注解注入刚刚定义的接口。这样的代码有更易维护,代码逻辑与配置分离等优点。代码如下:
package com.ivan.client.feign.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ivan.client.feign.entity.User;
import com.ivan.client.feign.service.UserService;
@RestController
public class ConsumerUserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/consumer/user/{id}")
public User getUser(@PathVariable(value = "id") Integer id) {
return userService.getUser(id);
}
@RequestMapping(value = "/consumer/user/create", method = RequestMethod.GET)
public User createUserPerson() {
User user = new User();
user.setName("张山");
user.setAge(18);
user = userService.create(user);
System.out.println(user.getId());
return user;
}
}
运行上面代码发现客户端已经自动实现了Ribbon的负载能力。
Spring Cloud都为我们加载了那些Feign相关的对象
在代码里应用上Feign,能够让我们的代码具有更好的维护性,那Spring Cloud是如何做到的呢?从上面的代码上看我们至少可以得到如下猜测:
- 通过FeignClient注解,我们得到的UserService对象一定是通过FeignBuilder构造出来的对象,这样才可能具备访问第三方接口的能力。
- 我们在接口方法里用到的注解都是Spring MVC的注解,Spring Cloud一定提供了某种转换器将Spring MVC的注解转成Feign内部的注解。
- Spring Cloud应该提供了某些编解码器来对请求需要发送的对象与得到的对象进行编解码。
EnableFeignClients里的秘密
在启动类上,我们加上了EnableFeignClients这个注解,那这个注解到底为我们做了那些工作呢,打开这个类的源码,我们可以看到如下代码:
看到FeignClientRegistrar类,你应该可以猜测到这个类的功能应该就是将FeignClient注解的类注册到Spring IOC容器里。带着这样的猜测来看看FeignClientRegistrar类的注要代码。关键代码我都有加上相应的注释:
package org.springframework.cloud.netflix.feign;
/**
* @author Spencer Gibb
* @author Jakub Narloch
* @author Venil Noronha
*/
class FeignClientsRegistrar implements ImportBeanDefinitionRegistrar,
ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
registerDefaultConfiguration(metadata, registry);
registerFeignClients(metadata, registry);
}
private void registerDefaultConfiguration(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
Map<String, Object> defaultAttrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
String name;
if (metadata.hasEnclosingClass()) {
name = "default." + metadata.getEnclosingClassName();
}
else {
name = "default." + metadata.getClassName();
}
registerClientConfiguration(registry, name,
defaultAttrs.get("defaultConfiguration"));
}
}
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
Set<String> basePackages;
Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName());
//这里定义了注解的过滤器,只有FeignClient注解才会被筛出来
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
FeignClient.class);
final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) {
scanner.addIncludeFilter(annotationTypeFilter);
basePackages = getBasePackages(metadata);
}
else {
final Set<String> clientClasses = new HashSet<>();
basePackages = new HashSet<>();
for (Class<?> clazz : clients) {
basePackages.add(ClassUtils.getPackageName(clazz));
clientClasses.add(clazz.getCanonicalName());
}
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
@Override
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
}
for (String basePackage : basePackages) {
Set<BeanDefinition> candidateComponents = scanner
.findCandidateComponents(basePackage);
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(
FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name,
attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
}
/**
*
这个方法很重要噢,里面将@FeignClient注解定义的类转成BeanDefinition对象,这样Spring IOC容器就有办法帮我们生成具体的FeignClient注解里定义的实例了。注意这里的BeanDefinition对象的实例是FeignClientFactoryBean对象,从这个对象中我们知道他一定提供了getObject方法,而这个方法里一定是调用了Feign Builder。
*/
private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientFactoryBean.class);
validate(attributes);
definition.addPropertyValue("url", getUrl(attributes));
definition.addPropertyValue("path", getPath(attributes));
String name = getName(attributes);
definition.addPropertyValue("name", name);
definition.addPropertyValue("type", className);
definition.addPropertyValue("decode404", attributes.get("decode404"));
definition.addPropertyValue("fallback", attributes.get("fallback"));
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
String alias = name + "FeignClient";
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
boolean primary = (Boolean)attributes.get("primary"); // has a default, won't be null
beanDefinition.setPrimary(primary);
String qualifier = getQualifier(attributes);
if (StringUtils.hasText(qualifier)) {
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
new String[] { alias });
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
}
FeignClientFactoryBean 这个类里有个关键的方法。feign方法会查找容器里定义的Encoder,Decoder与Contract类。
FeignClientsConfiguration
FeignClientsConfiguration 这个类属于Spring-cloud-netflix-core包里的类。依然继承了Spring Boot的优良传统,这个包里的大多数类会根据实际应用加载的包来为我们初使化Spring IOC容器里的对象。以下是FeignClientsConfigurationo的代码,
package org.springframework.cloud.netflix.feign;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder;
import org.springframework.cloud.netflix.feign.support.SpringDecoder;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.cloud.netflix.feign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import com.netflix.hystrix.HystrixCommand;
import feign.Contract;
import feign.Feign;
import feign.Logger;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.hystrix.HystrixFeign;
/**
* @author Dave Syer
* @author Venil Noronha
*/
@Configuration
public class FeignClientsConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Autowired(required = false)
private List<AnnotatedParameterProcessor> parameterProcessors = new ArrayList<>();
@Autowired(required = false)
private List<FeignFormatterRegistrar> feignFormatterRegistrars = new ArrayList<>();
@Autowired(required = false)
private Logger logger;
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(this.messageConverters));
}
@Bean
@ConditionalOnMissingBean
public Encoder feignEncoder() {
return new SpringEncoder(this.messageConverters);
}
@Bean
@ConditionalOnMissingBean
public Contract feignContract(ConversionService feignConversionService) {
return new SpringMvcContract(this.parameterProcessors, feignConversionService);
}
@Bean
public FormattingConversionService feignConversionService() {
FormattingConversionService conversionService = new DefaultFormattingConversionService();
for (FeignFormatterRegistrar feignFormatterRegistrar : feignFormatterRegistrars) {
feignFormatterRegistrar.registerFormatters(conversionService);
}
return conversionService;
}
@Configuration
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
protected static class HystrixFeignConfiguration {
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "feign.hystrix.enabled", matchIfMissing = false)
public Feign.Builder feignHystrixBuilder() {
return HystrixFeign.builder();
}
}
@Bean
@ConditionalOnMissingBean
public Retryer feignRetryer() {
return Retryer.NEVER_RETRY;
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public Feign.Builder feignBuilder(Retryer retryer) {
return Feign.builder().retryer(retryer);
}
@Bean
@ConditionalOnMissingBean(FeignLoggerFactory.class)
public FeignLoggerFactory feignLoggerFactory() {
return new DefaultFeignLoggerFactory(logger);
}
}
从代码里我们可以知道:
- 容器默认为我们注入了ResponseEntityDecoder作为系统的解码器。
- 容器默认为我们注入了SpringEncoder作为系统的编码器,底层还是用的Spring MVC的 messageConverters。
- 容器为我们注入了SpringMvcContract这个类作为Spring MVC的注解到Feign注解的转换。
我们可以看看SpringMvcContract这个类是如何将Spring MVC的注解转成Feign注解的。下面截取部分代码并加上了相应的注释如下:
/**
这个方法用于处理定义在方法上的注解,
**/
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
Annotation methodAnnotation, Method method) {
//方法上必需要有RequestMapping 这个注解,否则不进行处理
if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
.annotationType().isAnnotationPresent(RequestMapping.class)) {
return;
}
RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
// HTTP Method
RequestMethod[] methods = methodMapping.method();
if (methods.length == 0) {
methods = new RequestMethod[] { RequestMethod.GET };
}
checkOne(method, methods, "method");
//MethodMetadata 为Feign内部的对象,里面提供了各种方法用于设置需要发送请求的元数据信息,如请求的方法与URL,
data.template().method(methods[0].name());
// path
checkAtMostOne(method, methodMapping.value(), "value");
if (methodMapping.value().length > 0) {
String pathValue = emptyToNull(methodMapping.value()[0]);
if (pathValue != null) {
pathValue = resolve(pathValue);
// Append path from @RequestMapping if value is present on method
if (!pathValue.startsWith("/")
&& !data.template().toString().endsWith("/")) {
pathValue = "/" + pathValue;
}
data.template().append(pathValue);
}
}
//处理rest请求的生产者
// produces
parseProduces(data, method, methodMapping);
//处理rest请求的消费者
// consumes
parseConsumes(data, method, methodMapping);
// headers
parseHeaders(data, method, methodMapping);
data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
/**
无非在请求头里加个Accept这个参数
**/
private void parseProduces(MethodMetadata md, Method method,
RequestMapping annotation) {
checkAtMostOne(method, annotation.produces(), "produces");
String[] serverProduces = annotation.produces();
String clientAccepts = serverProduces.length == 0 ? null
: emptyToNull(serverProduces[0]);
if (clientAccepts != null) {
md.template().header(ACCEPT, clientAccepts);
}
}
/**
无非在请求头里加上Content-type这个参数
**/
private void parseConsumes(MethodMetadata md, Method method,
RequestMapping annotation) {
checkAtMostOne(method, annotation.consumes(), "consumes");
String[] serverConsumes = annotation.consumes();
String clientProduces = serverConsumes.length == 0 ? null
: emptyToNull(serverConsumes[0]);
if (clientProduces != null) {
md.template().header(CONTENT_TYPE, clientProduces);
}
}