OpenFeign远程调用详解【微服务篇】

目录

[一 什么是openfeign](#一 什么是openfeign)

[二 怎么使用](#二 怎么使用)

1.导入依赖

2.编写FeignClient接口

3.使用注解开启openfeign功能


一 什么是openfeign

在使用之前,我们需要先知道openfeign是什么?以及它的功能是什么?在哪里需要使用它。那么接下来我们先通过一张流程图来进行一个了解。

这是一个我们发送请求到controller,然后服务器接收我们的请求,但是因为我们使用的是微服务,也就是各个服务分开独立 。我的初始请求是请求到服务器1,但是现在我需要服务器2中的数据,那么我需要向服务器2 发送请求来获得我需要的数据。而两个服务器之间如何发送请求?这就是openfeign的功能。

二 怎么使用

那么了解了openfeign之后,我们就来看看如何使用它。

1.导入依赖

openfeign需要把导入两个依赖,一个是openfeign,一个负载均衡,因为openfeign在发送请求的时候需要对集群服务使用负载均衡算法得到最终发送请求的服务实例。

XML 复制代码
        <!--OpenFeign -->
        <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>

2.编写FeignClient接口

java 复制代码
package com.feisi.clients;
import com.fei.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 用户http的客户端接口
 */
@RequestMapping("user")
@FeignClient("user-service")    //@FeignClient 表示该接口是OpenFeign的客户端接口
public interface UserClient {
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Integer id);
}

3.使用注解开启openfeign功能

最后只需要在启动类使用注解@EnableFeignClients("com.feisi.clients")来开启这个注解,括号里面填的是你的上面那个接口的全限定名,这样才能扫描到。

相关推荐
隔窗听雨眠17 小时前
大模型加爬虫上篇:技术融合与架构革新
爬虫·架构
Vergelight18 小时前
实战拆解|三类RAG架构差异:朴素、进阶、多轮RAG落地选型指南
架构·大模型·aigc·agent·ai产品经理·转行·ai后台设计
java_cj19 小时前
深入kube-apiserver认证机制:从Bearer Token到mTLS的完整认证链解析
linux·运维·服务器·云原生·容器·kubernetes
Database_Cool_19 小时前
大规模数据分析降本指南:AnalyticDB Serverless 弹性架构实战
数据仓库·阿里云·架构·数据分析·serverless
绿算技术19 小时前
Mooncake 与绿算ForinnBase GroundPool如何联手打破推理僵局?
科技·算法·架构
阿米亚波19 小时前
【Windows】QEMU 启动 openEuler aarch64/arm64 架构系统 + 离线软件源
linux·windows·经验分享·笔记·架构·arm
taocarts_bidfans20 小时前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
by————组态21 小时前
Ricon组态系统 - 新一代Web可视化组态平台
前端·后端·物联网·架构·组态·组态软件
@insist12321 小时前
系统架构设计师-5G 技术、冗余设计与分层架构
5g·架构·系统架构·软考·系统架构设计师·软件水平考试
yspwf1 天前
NestJS 配置管理完整方案
后端·架构·node.js