文章目录
1、介绍
Feign是一种负载均衡的HTTP客户端, 使用Feign调用API就像调用本地方法一样,从避免了 调用目标微服务时,需要不断的解析/封装json 数据的繁琐。基于注解来实现,具备可插拔的特性;
2、使用
2.1、 面向接口编程,配置@FeginClien注解的接口
test项目里面配置@FeginClien注解的接口,name为Eureka中注册的服务名,区分大小写
2.2、导入pom依赖
其它项目想要调用test项目,则导入pom依赖
2.3、开启Feign配置,扫描@FeginClient注解:
开启Feign配置,扫描@FeginClient注解,为服务器包名(项目名:a-b-c 包名:aBc)
3、更新包
1、test项目deploy 一下,将包更新到maven仓库
2、 其它项目想要获取Maven上面的更新包,直接更新可能会更新不下来
2.1、 找到maven仓库地址,手动删除原来包,再点击更新
2.2、 如果你有两个maven仓库,切换仓库,再点击更新
4、排除包的其他接口
当A项目引用的test项目的包时,A项目的swagger会显示A+test两个项目的全部接口,但是此时我只想要自己项目的接口,不需要fegin其他项目的接口显示出来
解决方案
添加FeignConfiguration类,重新启动
FeignConfiguration .java
package com.seasky.middlegroundadmin.config;
import feign.Feign;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
@Configuration
@ConditionalOnClass({Feign.class})
public class FeignConfiguration {
@Bean
public WebMvcRegistrations feignWebRegistrations() {
return new WebMvcRegistrations() {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new FeignRequestMappingHandlerMapping();
}
};
}
private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected boolean isHandler(Class<?> beanType) {
if(AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class)) {
return super.isHandler(beanType) &&
(beanType.getName().indexOf("com.seasky.middlegroundadmin") >= 0 ||
!AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class));
} else {
return super.isHandler(beanType);
}
}
}
}