Spring Cloud 是目前最火的微服务框架, Feign 作为基础组件之一, 在 Spring Cloud 体系中发挥了重要的作用.
一, FeignClient 注解
FeignClient 注解被 @Target(ElementType.TYPE) 修饰, 表示 FeignClient 注解的作用目标在接口上
- //@FeignClient(value = "fast-maindata-service",contextId = "MaindataServiceClient")
- @FeignClient(url = "47.100.79.142:30041",name = "MaindataServiceClient")
- public interface MaindataServiceClient extends IMaindataPharmacyController {
- }
声明接口之后, 在代码中通过 @Resource 注入之后即可使用.@FeignClient 标签的常用属性如下:
name: 指定 FeignClient 的名称, 如果项目使用了 Ribbon,name 属性会作为微服务的名称, 用于服务发现
url: url 一般用于调试, 可以手动指定 @FeignClient 调用的地址
decode404: 当发生 http 404 错误时, 如果该字段位 true, 会调用 decoder 进行解码, 否则抛出 FeignException
configuration: Feign 配置类, 可以自定义 Feign 的 Encoder,Decoder,LogLevel,Contract
fallback: 定义容错的处理类, 当调用远程接口失败或超时时, 会调用对应接口的容错逻辑, fallback 指定的类必须实现 @FeignClient 标记的接口
fallbackFactory: 工厂类, 用于生成 fallback 类示例, 通过这个属性我们可以实现每个接口通用的容错逻辑, 减少重复的代码
path: 定义当前 FeignClient 的统一前缀
- @FeignClient(name = "github-client",
- url = "https://api.github.com",
- configuration = GitHubExampleConfig.class,
- fallback = GitHubClient.DefaultFallback.class)
- public interface GitHubClient {
- @RequestMapping(value = "/search/repositories", method = RequestMethod.GET)
- String searchRepo(@RequestParam("q") String queryStr);
- /**
- * 容错处理类, 当调用失败时, 简单返回空字符串
- */
- @Component
- public class DefaultFallback implements GitHubClient {
- @Override
- public String searchRepo(@RequestParam("q") String queryStr) {
- return "";
- }
- }
- }
在使用 fallback 属性时, 需要使用 @Component 注解, 保证 fallback 类被 Spring 容器扫描到, GitHubExampleConfig 内容如下:
- @Configuration
- public class GitHubExampleConfig {
- @Bean
- Logger.Level feignLoggerLevel() {
- return Logger.Level.FULL;
- }
- }
在使用 FeignClient 时, Spring 会按 name 创建不同的 ApplicationContext, 通过不同的 Context 来隔离 FeignClient 的配置信息, 在使用配置类时, 不能把配置类放到 Spring App Component scan 的路径下, 否则, 配置类会对所有 FeignClient 生效.
关于调用目前有两种:
1, 接口提供方在注册中心.
如果服务提供方已经注册到注册中心了, 那么 name 或者 value 的值为: 服务提供方的服务名称. 必须为所有客户端指定一个 name 或者 value
@FeignClient(value="run-product",fallback = ProductClientServiceFallBack.class)
2, 单独的一个 http 接口, 接口提供方没有注册到注册中心.
@FeignClient(name="runClient11111",url="localhost:8001")
此处 name 的值为: 调用客户端的名称.
以上两种方式都能正常调用. name 可以为注册中心的实例名称, 加上 url 属性时, name 的值就与注册中心实例名称无关. 至于 url 属性和 name 属性的关系请指导的大佬们留言呀.
来源: http://www.bubuko.com/infodetail-3682110.html