Fegin远程调用

文章介绍了Fegin在微服务架构中的使用步骤,包括引入依赖、启用注解和创建客户端接口。接着讨论了Fegin的优化,特别是通过使用ApacheHttpClient来支持连接池,并提供了配置连接池的示例。最后提出了最佳实践,包括接口继承和FeginClient的模块化抽取。
摘要由CSDN通过智能技术生成

一、Fegin的使用

        1、在一个微服务下引入依赖

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

        2、添加注解

             在启动类上加注解@EnableFeginClients开启Fegin

        3、添加一个接口,编写fegin客户端

            如:

@FeignClient("userservice")
public interface UserClient {
    @GetMapping("/user/{id}")
    User findById(@PathVariable("id") Long id);
}

 总结:Fegin就是提取一个微服务中接口,封装成一个通用的接口,供其他微服务使用。

二、Fegin使用优化

Feign底层发起http请求,依赖于其它的框架。其底层客户端实现包括:

  •URLConnection:默认实现,不支持连接池

  •Apache HttpClient :支持连接池

  •OKHttp:支持连接池

        1、引入依赖

        使用Apache HttpClient

<!--httpClient的依赖 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

         2、配置连接池

              在application.yml中添加配置

feign:
  client:
    config:
      default: # default全局的配置
        loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息,推荐使用
  httpclient:
    enabled: true # 开启feign对HttpClient的支持
    max-connections: 200 # 最大的连接数
    max-connections-per-route: 50 # 每个路径的最大连接数

总结:1.日志级别尽量用basic

           2.使用HttpClient或OKHttp代替URLConnection

                ① 引入feign-httpClient依赖

                ② 配置文件开启httpClient功能,设置连接池参数

 

三、最佳实践

        1、继承方式

                服务提供者

public interface UserApi {
    @GetMapper("user/{id}")
    User findById(@PathVariable("id") Long id);
}

                 Fegin客户端,继承。消费者,调用Fegin客户端接口

@FeginClient(value = "userservice")
public interface UserClient extends UserApi{}

         2、抽取

                将Fegin的Client抽取成独立的微服务模块,并将有关的实体放到fegin-api模块中。

                引入模块依赖,进行远程调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值