先前我们学习了Spring Cloud注册服务和使用Ribbon+RestTemplate进行消费服务。现在
我们再来学习另外一种调用服务方式——Fegin。
Feign是一种声明式、模板化的HTTP客户端。与Ribbo相比使用起来更加方便的。
Fegin采用接口的方式,只需要创建一个接口,然后在上面添加注解即可,
将需要调用的其他服务的方法定义成抽象方法即可,
不需要自己构建 http 请求。然后就像是调用自身工程的方法调用,
而感觉不到是调用远程方法,使得编写客户端变得非常容易。
我们复用之前的编写的Eureka注册中心工程。
先添加EurekaClientFeign子模块
pom.xml内引入相应依赖,配置如下
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>EurekaDemoartifactId>
<groupId>com.smallstepgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>EurekaClientFeignartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
dependencies>
project>
application.yml配置内容如下:
server:
port: 8700
spring:
application:
name: consumer
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9000/eureka/
添加启动类并在启动类上增加@EnableFeignClients注解,内容如下
@SpringBootApplication
@EnableFeignClients
public class EurekaClientFeginApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientFeginApplication.class, args);
}
}
添加完启动类,并添加FeignClient客户端,内容如下:
@FeignClient("producer")
public interface MessagesFeignClient {
@GetMapping(value = "/get")
String getName(@RequestParam(value = "name") String name);
}
其中@FeignClient的value为提供服务注册到注册中心的clientId。
并且定义了个Get接口。
再编写一个control类来调用FeignClient,内容如下:
@RestController
public class MessageController {
@Autowired
MessagesFeignClient messagesFeignClient;
@GetMapping("/show")
public String showMessage(@RequestParam String name){
//producer 为提供的服务注入到eureka的名称
return messagesFeignClient.getName(name);
}
}
其中通过@Autowired自动注入MessagesFeignClient,并调用相对应代码。
客户端编写完成后,启动注册中心和俩个提供服务工程。再启动
编写好的FeignClient,进行访问http://127.0.0.1:8700/show?name=IT_LiGe
即可出现如下界面,完成消费。
Hi IT_LiGe ,I am from port:8001
或者
Hi IT_LiGe ,I am from port:8002
启动类通过添加@EnableFeignClients注来扫描所有使用注解@FeignClient定义的feign客户端。
具体如何实现呢?
查看EnableFeignClients内容,内容如下
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({FeignClientsRegistrar.class})
public @interface EnableFeignClients {
String[] value() default {};
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
Class<?>[] defaultConfiguration() default {};
Class<?>[] clients() default {};
}
可以看到Import了FeignClientsRegistrar类,再跟踪
FeignClientsRegistrar类,发现其实现ImportBeanDefinitionRegistrar,
ResourceLoaderAware, EnvironmentAware类,进行
自定义扫描,默认会调用registerBeanDefinitions方法,
registerBeanDefinitions方法如下:
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
this.registerDefaultConfiguration(metadata, registry);
this.registerFeignClients(metadata, registry);
}
该方法又调用registerDefaultConfiguration和registerFeignClients方法,
查看registerFeignClients方法内容,内容如下
public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = this.getScanner();
scanner.setResourceLoader(this.resourceLoader);
Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(FeignClient.class);
Class<?>[] clients = attrs == null?null:(Class[])((Class[])attrs.get("clients"));
Object basePackages;
if(clients != null && clients.length != 0) {
final Set<String> clientClasses = new HashSet();
basePackages = new HashSet();
Class[] var9 = clients;
int var10 = clients.length;
for(int var11 = 0; var11 < var10; ++var11) {
Class<?> clazz = var9[var11];
((Set)basePackages).add(ClassUtils.getPackageName(clazz));
clientClasses.add(clazz.getCanonicalName());
}
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(new FeignClientsRegistrar.AllTypeFilter(Arrays.asList(new TypeFilter[]{filter, annotationTypeFilter})));
} else {
scanner.addIncludeFilter(annotationTypeFilter);
basePackages = this.getBasePackages(metadata);
}
Iterator var17 = ((Set)basePackages).iterator();
while(var17.hasNext()) {
String basePackage = (String)var17.next();
Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
Iterator var21 = candidateComponents.iterator();
while(var21.hasNext()) {
BeanDefinition candidateComponent = (BeanDefinition)var21.next();
if(candidateComponent instanceof AnnotatedBeanDefinition) {
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 = this.getClientName(attributes);
this.registerClientConfiguration(registry, name, attributes.get("configuration"));
this.registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
}
通过扫描指定包下使用@FeignClient注解类并最终this.registerFeignClient进行注入。
registerFeignClient方法内容如下:
private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
this.validate(attributes);
definition.addPropertyValue("url", this.getUrl(attributes));
definition.addPropertyValue("path", this.getPath(attributes));
String name = this.getName(attributes);
definition.addPropertyValue("name", name);
String contextId = this.getContextId(attributes);
definition.addPropertyValue("contextId", contextId);
definition.addPropertyValue("type", className);
definition.addPropertyValue("decode404", attributes.get("decode404"));
definition.addPropertyValue("fallback", attributes.get("fallback"));
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
definition.setAutowireMode(2);
String alias = contextId + "FeignClient";
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
boolean primary = ((Boolean)attributes.get("primary")).booleanValue();
beanDefinition.setPrimary(primary);
String qualifier = this.getQualifier(attributes);
if(StringUtils.hasText(qualifier)) {
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[]{alias});
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
可以发现进行获取@FeignClient的值进行复制给FeignClientFactoryBean然后最终注入
的对象为FeignClientFactoryBean的getObject(),查看
FeignClientFactoryBean的getObject()方法又调用了getTarget()方法。
getTarget()方法如下:
<T> T getTarget() {
FeignContext context = (FeignContext)this.applicationContext.getBean(FeignContext.class);
Builder builder = this.feign(context);
if(!StringUtils.hasText(this.url)) {
if(!this.name.startsWith("http")) {
this.url = "http://" + this.name;
} else {
this.url = this.name;
}
this.url = this.url + this.cleanPath();
return this.loadBalance(builder, context, new HardCodedTarget(this.type, this.name, this.url));
} else {
if(StringUtils.hasText(this.url) && !this.url.startsWith("http")) {
this.url = "http://" + this.url;
}
String url = this.url + this.cleanPath();
Client client = (Client)this.getOptional(context, Client.class);
if(client != null) {
if(client instanceof LoadBalancerFeignClient) {
client = ((LoadBalancerFeignClient)client).getDelegate();
}
builder.client(client);
}
Targeter targeter = (Targeter)this.get(context, Targeter.class);
return targeter.target(this, builder, context, new HardCodedTarget(this.type, this.name, url));
}
}
可以看到根据@FeignClient注解配置的url进行判断,如何配置使用的this.loadBalance,
否则使用的targeter.target。进行查看loadBalance最终发现都调用targeter.target,
只是使用的httpclient不同。targeter默认实现类为DefaultTargeter再跟踪targeter.target最终调用如下
public <T> T target(Target<T> target) {
return this.build().newInstance(target);
}
public Feign build() {
Factory synchronousMethodHandlerFactory = new Factory(this.client, this.retryer, this.requestInterceptors, this.logger, this.logLevel, this.decode404, this.closeAfterDecode, this.propagationPolicy);
ParseHandlersByName handlersByName = new ParseHandlersByName(this.contract, this.options, this.encoder, this.decoder, this.queryMapEncoder, this.errorDecoder, synchronousMethodHandlerFactory);
return new ReflectiveFeign(handlersByName, this.invocationHandlerFactory, this.queryMapEncoder);
}
发现最终都是ReflectiveFeign实例,再查看ReflectiveFeign.newInstance的
到内容,发现最终是一个代理类。看到这里我们可以知道,所有加@FeignClient注解的
最终的实现其实就是ReflectiveFeign$FeignInvocationHandler动态代理。
再跟踪发现FeignInvocationHandler最终交给SynchronousMethodHandler处理,
查看SynchronousMethodHandler的invoke方法,其调用内部executeAndDecode方法。
executeAndDecode关键代码如下:
Object executeAndDecode(RequestTemplate template, Options options) throws Throwable {
Request request = this.targetRequest(template);
//...省略其他代码
Response response;
try {
response = this.client.execute(request, options);
} catch (IOException var16) {
if(this.logLevel != Level.NONE) {
this.logger.logIOException(this.metadata.configKey(), this.logLevel, var16, this.elapsedTime(start));
}
throw FeignException.errorExecuting(request, var16);
}
//...省略其他代码
}
其中先执行this.targetRequest进行请求拦截器处理,然后通过this.client.execute进行调用接口。
client默认是LoadBalancerFeignClient,最终使用Ribbon的客户端负载均衡功能。
再回头看看@FeignClient注解类内容如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
@AliasFor("name")
String value() default "";
/** @deprecated */
@Deprecated
String serviceId() default "";
String contextId() default "";
@AliasFor("value")
String name() default "";
String qualifier() default "";
String url() default "";
boolean decode404() default false;
Class<?>[] configuration() default {};
Class<?> fallback() default void.class;
Class<?> fallbackFactory() default void.class;
String path() default "";
boolean primary() default true;
}
其中value和name相同为serviceId;
fallback和fallbackFactory为熔断回调处理后面会再介绍如何使用。
configuration为自定义配置文件。
url为指定特定地址
path为路径前缀
通过上述源码分析,我们知道在发起调用服务之前会执行this.targetRequest(template)进行遍历所有的RequestInterceptor的实现类,然后
调用实现类的apply方法。因此我们只要编写一个RequestInterceptor实现类注入到Spring容器内即可。
RequestInterceptor实现类代码如下:
@Component
public class MyRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("token","IT_LiGe_Token");
}
}
实现在每个请求增加头部token。
然后修改俩个提供服务的工程内MessageController返回token内容。修改内容如下:
@RestController
public class MessageController {
@Value("${server.port}")
String port;
@GetMapping("/get")
public String getMessage(@RequestParam("name")String name, @RequestHeader("token") String token){
return "Hi " + name + " ,I am from port:" + port + ",token:" +token;
}
}
修改完成后,重新服务。再次访问http://127.0.0.1:8700/show?name=IT_LiGe,可以看到打印出我们
设置的Token值。如下
Hi IT_LiGe ,I am from port:8001,token:IT_LiGe_Token
或者
Hi IT_LiGe ,I am from port:8002,token:IT_LiGe_Token
源代码地址:https://gitee.com/LeeJunProject/spring_cloud_learning/tree/master/eureka/EurekaDemo
欢迎扫描下图关注公众号 IT李哥,公众号经常推送一些优质的技术文章