Feign 简介

Spring Cloud Feign 是一个 HTTP 请求调用的轻量级框架,可以以 Java 接口注解的方式调用 HTTP 请求,而不用通过封装 HTTP 请求报文的方式直接调用

Feign 通过处理注解,将请求模板化,当实际调用的时候传入参数,根据参数再应用到请求上,进而转化成真正的请求

第一个 Feign 程序

本小节介绍如何通过 Nacos+Feign 实现服务之间的调用,新建 server-01、server-02 项目,并分别注册 Nacos

server-01 引入依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

新建 Server02FeignClient 接口,用于调用 server-02 提供的对外接口

// name:要调用的服务名
FeignClient(name = "server-02")
public interface Server02FeignClient { @GetMapping("/test/getConfig")
void getConfig();
}

启动类加上注解 @EnableFeignClients

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Server01Application { public static void main(String[] args) {
SpringApplication.run(Server01Application.class, args);
}
}

使用 Server02FeignClient 调用 server-02 的接口

@Slf4j
@RestController
public class TestCon { @Autowired
private Server02FeignClient server02FeignClient; @GetMapping("/test/getConfigByFeign")
public void getConfigByFeign() {
server02FeignClient.getConfig();
}
}

在 server-02 创建接口

@Slf4j
@RestController
public class TestCon { @Value("${test.value}")
private String testValue; @Value("${spring.application.name}")
private String applicationName; @Value("${server.port}")
private String port; @GetMapping("/test/getConfig")
public void getConfig() {
log.info("testValue: {} by {}-{}", testValue, applicationName, port);
}
}

调用 server-01 的 /test/getConfigByFeign 接口,就会通过 Feign 调用 server-02 的 /test/getConfig 接口

@FeignClient 注解可作用在类、接口、枚举上,主要包含如下属性:

  • name/value:name 是 vaue 的别名,value 也是 name 的别名,两者的作用是一致的,用指定 FeignClient 的名称,如果配合注册中心使用,则作为微服务的名称,用于服务发现

  • url:主要用于调试,可以手动指定 @FeignClient 调用的地址

  • path:path 用于定义当前 FeignClient 的统一前缀

  • contextld:如果要创建多个具有相同名称或 URL 的 Feign 客户端,以便它们指向同一台服务器,但是每个客户端具有不同的自定义配置,则必须使用 contextId 属性,以避免这些配置的名称冲突

@FeignClient(contextId = "fooClient", name = "stores", configuration=FooConfiguration.class)
public interface FooClient {...} @FeignClient(contextId = "barClient", name = "stores", configuration=BarConfiguration.class)
public interface BarClient {...}
  • fallback/fallbackFactory:

  • fallback:定义容错的处理类,当调用远程接口失败或超时时,就会调用对应接口的容错逻辑,falback 指定的类必须实现 @FeignClient 标记的接口

  • fallbackFactory:工厂类,用于生成 fallback 类,通过该属性可以实现每个接口通用的容错逻辑,减少重复的代码

  • decode404:当发生 404 错误时,如果该字段为 true,就会调用 decoder 进行解码,否则抛出异常

  • Configuration:Feign 配置类可以自定义 Feign 的 Encoder、Decoder、LogLevel、Contract 等,OpenFeign 默认为 Feign 提供以下对象(bean 类型 bean 名称 : 类名称):

  • Decoder feignDecoder : ResponseEntityDecoder

  • Encoder feignEncoder : SpringEncoder

  • Logger feignLogger : Slf4jLogger

  • Contract feignContract : SpringMvcContract

  • FeignBuilder feignBuilder : HystrixFeignBuilder

spring-cloud-starter-openfeign 支持 spring-cloud-starter-netflix-ribbon 和 spring-cloud-starter.loadbalancer,如果 Ribbon 在类路径中且已启用,则 Client feignClient 是 LoadBalancerFeignClient,如果 SpringCloud LoadBalancer 在类路径中,则使用 FeignBlockingLoadBalancerClient

默认情况下,Spring Cloud OpenFeign 不会为 Feign 提供以下 bean 对象,但是仍然会从应用程序上下文中查找这些类型的 bean 以创建 Feign 客户端:

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

以上是通过注解 @FeignClient 的配置属性进行配置的,我们也可以使用配置文件进行配置

feign:
client:
config:
feignName:
connectTimeout: 5000
readTimeout:5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example,SimpleRetryer
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example,BarRequestInterceptor
decode404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract

可以在 @EnableFeignClients 属性 defaultConfiguration 中指定默认配置,不同之处在于此配置将适用于所有 Feign 客户端

如果希望使用配置文件来配置所有 @FeignClient,则可以使用默认 Feign 名称创建配置属性,例如:

feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic

如果同时创建 @Configuration bean 和配置文件,则配置文件将覆盖 @Configuration 值,如果要将优先级更改为 @Configuration,就可以将 feign.client.default-to-properties 更改为 false

Feign 传参

以下服务端接口可通过 Get 或 Post 请求调用并接收参数

@RequestMapping("/test/testFeignWithParam")
public void testFeignWithParam(@RequestParam String name,
@RequestParam int age) {
log.info("testFeignWithParam: name-{}, age-{}", name, age);
}

通过在 Url 拼接请求传参如下:

@FeignClient(name = "server-02", path = "server-02")
public interface Server02FeignClient { @GetMapping("/test/testFeignWithParam?name=zhanghsan&age=66")
//@PostMapping("/test/testFeignWithParam?name=zhanghsan&age=66")
void testFeignWithParam();
}

使用 @RequestParam 传参如下:

@FeignClient(name = "server-02", path = "server-02")
public interface Server02FeignClient { //@GetMapping("/test/testFeignWithParam")
@PostMapping("/test/testFeignWithParam")
void testFeignWithParam(@RequestParam("name") String name,
@RequestParam("age") int age);
}

也可以使用 OpenFeign 的 @QueryMap 将请求实体作为参数的映射,不过由于 @QueryMap 注解与 Spring 不兼容,所以 OpenFeign 提供了等效的 @SpringQueryMap 注解

@FeignClient(name = "server-02", path = "server-02")
public interface Server02FeignClient { //@GetMapping("/test/testFeignWithQueryMap")
@PostMapping("/test/testFeignWithQueryMap")
void testFeignWithQueryMap(@SpringQueryMap FeignParam param);
}

声明式调用 —— SpringCloud OpenFeign的更多相关文章

  1. SpringCloud之Feign声明式调用原理及配置

    1 什么是Feign Feign是一种声明式.模板化的HTTP客户端(仅在Application Client中使用).声明式调用是指,就像调用本地方法一样调用远程方法,无需感知操作远程http请求. ...

  2. SpringCloud OpenFeign Post请求的坑

    在微服务开发中SpringCloud全家桶集成了OpenFeign用于服务调用,SpringCloud的OpenFeign使用SpringMVCContract来解析OpenFeign的接口定义. 但 ...

  3. 声明式调用---Feign

    Feign:Feign是一种声明式.模板化的HTTP客户端. 用我的理解来说,Feign的功能类似dubbo暴露服务,但是与dubbo稍有不同的是Feign是HTTP REST接口的形式暴露的. 这一 ...

  4. SpringCloud Alibaba实战(8:使用OpenFeign服务调用)

    源码地址:https://gitee.com/fighter3/eshop-project.git 持续更新中-- 在上一个章节,我们已经成功地将服务注册到了Nacos注册中心,实现了服务注册和服务发 ...

  5. SpringCloud学习笔记(3):使用Feign实现声明式服务调用

    简介 Feign是一个声明式的Web Service客户端,它简化了Web服务客户端的编写操作,相对于Ribbon+RestTemplate的方式,开发者只需通过简单的接口和注解来调用HTTP API ...

  6. Spring-Cloud之Sleuth链路追踪-8

    一.Spring Cloud Sleuth 是Spring Cloud 的一个组件,它的主要功能是在分布式系统中提供服务链路追踪的解决方案. 二.为什么需要Spring Cloud Sleuth? 微 ...

  7. SpringCloud微服务治理技术入门(SCN)

    1.集群.分布式.微服务 首先先理解三个感念 什么是集群?: 同一个业务,部署在多个服务器上,目的是实现高可用,保证节点可用! 什么是分布式?: 一个业务分拆成多个子业务,部署在不同的服务器上,每个子 ...

  8. SpringCloud学习目录

    Spring Cloud直接建立在Spring Boot的企业Java创新方法上,它通过实现经过验证的模式来简化分布式.微服务风格的体系结构,从而为您的微服务带来弹性.可靠性和协调. 以上来自spri ...

  9. 微服务SpringCloud无法进行服务消费

    最近用SpringCloud做微服务,一直无法成功进行服务消费. 我使用的服务消费者是Feign,声明式调用服务提供者. 排查过程 1.检查服务提供者: (1)对提供的方法进行测试,确保提供的服务没有 ...

  10. SpringCloud微服务实战二:Spring Cloud Ribbon 负载均衡 + Spring Cloud Feign 声明式调用

    1.Spring Cloud Ribbon的作用 Ribbon是Netflix开发的一个负载均衡组件,它在服务体系中起着重要作用,Pivotal将其整合成为Spring Cloud Ribbon,与其 ...

随机推荐

  1. simple-check-100

    代码脚本解开法 #include <stdio.h> int main(int argc, char* argv[]) { char flag_data[] = { 220, 23, 19 ...

  2. String 的 indexOf 与 search 方便的区别

    String 这个对象里面包含许多方法 今天只要讲 indexOf 与 search 1.indexOf stringObject.indexOf(searchvalue,fromindex) 2.s ...

  3. 探索 Web API:SpeechSynthesis 与文本语言转换技术

    一.引言 随着科技的不断发展,人机交互的方式也在不断演变.语音识别和合成技术在人工智能领域中具有重要地位,它们为残障人士和日常生活中的各种场景提供了便利.Web API 是 Web 应用程序接口的一种 ...

  4. 老是听到做PPT要会“内容可视化”,到底啥是内容可视化?

    在PPT中,内容可视化是指将文字.数据和概念等抽象信息转化为图像.图表.图表及其他可视化元素来呈现.通过合适的颜色.形状.大小和布局等视觉设计元素来强调信息的关键点和关系, 从而提高观众对信息的理解和 ...

  5. jmeter完成文件上传接口

    前提:测试项目中有一个上传本地文件(excel)测被测接口. 测试工具:jmeter 协议:http 测试项目如下图: 第一步:点击模板上传,选择本地excel文件 第二步:上传成功,系统识别exce ...

  6. DRF过滤器

    https://www.django-rest-framework.org/api-guide/filtering 一般情况下,我们可以重写DRF视图类的get_queryset()方法来实现查询结果 ...

  7. 信创选国产,Solon v2.6.3 发布

    Solon 是什么框架? Java 新的"生态级"应用开发框架.从零开始构建,有自己的标准规范与开放生态(历时六年,具备全球第二级别的生态规模). 相对于 Spring,有什么特点 ...

  8. 红日靶场5-wp

    红日靶场5 环境搭建 win7 账密及域 leo@sun 123.com sun\Administrator dc123.com 双网卡模拟内外网 外网网卡:192.168.130.150 内网网卡: ...

  9. Ubuntu基线指导手册

    Ubuntu基线指导手册 1.   身份鉴别策略组检测 准备: 安装一个PAM模块来启用cracklib支持,这可以提供额外的密码检查功能. 在Debian,Ubuntu或者Linux Mint使用命 ...

  10. .net Core中间件实战

    新建一个ASP.NET Core Web Application 项目选中空模板 然后为项目添加一个Microsoft.Extensions.Logging.Console 由于我用的.net cor ...