介绍

声明式的http客户端,底层还是HttpClient,可以解决RestTemplate硬编码进行远程服务调用的缺点

官网:https://github.com/OpenFeign/feign

入门

以A微服务对B微服务远程调用为例

若无多个微服务对B微服务调用的情况,第1、2步可在A微服务中完成

1.建立Feign模块并导入依赖

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

2.编写Feign的客户端BClient

BClient添加注解:@B

@B为B在nacos中的注册名

在使用Feign客户端接口时,强烈建议遵守如下几点要求:

  • 使用@RequestMapping注解

    古早版本只能识别@RequestMapping,便于与古早版本兼容

  • 请求参数需要指定参数名称

@FeignClient("BClient")
public interface BClient {
    @RequestMapping("/user/{id}")
    void findById(@PathVariable("id") Long id);
}

3.A引导类增加注解

@EnableFeignClients(basePackages = {"BClient所在目录绝对路径"})

4.远程调用

注入BClient便可直接调用

@Autowired
private BClient bClient;
public void findById(Long id){
    bClient.findById(id);
}

#.Feign集成HttpClient(非必须)

  1. A微服务中导入依赖

    <dependency>
        <groupId>io.github.openfeign</groupId>
        <artifactId>feign-httpclient</artifactId>
    </dependency>
    
  2. 配置文件

    feign:
      httpclient:
        enabled: true # 开启feign对HttpClient的支持
        max-connections: 200 # 最大的连接数
        max-connections-per-route: 50 # 每个路径的最大连接数
    
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。