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")来开启这个注解,括号里面填的是你的上面那个接口的全限定名,这样才能扫描到。

相关推荐
头茬韭菜7 小时前
第 1 篇:「Glass-Box 的骨架」——全景架构与六层数据流水线
架构·agent·semantica
奔跑的架构师9 小时前
[A-50]ARMv9/v8-DVFS系统架构
linux·arm开发·架构·系统架构·arm
闲云自留地9 小时前
动手玩 Nova:Hypervisor、主机聚合、可用分区、虚拟机生命周期实操
运维·架构·openstack
一航jason10 小时前
Android平台推理框架及试用场景模型对比
android·人工智能·ai·架构·ai编程·llama
Leo.yuan10 小时前
2026年多数据库实时同步的四种架构方案及工具推荐
数据库·架构
yychen_java12 小时前
第二篇:从世界模型到 Physical AI——一套可落地的工业智能体架构
人工智能·架构
Lsetea12 小时前
Kubernetes 1.37 Pod证书怎么签发:Signer与mTLS信任链排查
云原生·kubernetes·ssl证书·tls·mtls
六面体混凝土移动师14 小时前
我把 Cloudflare 开源了
架构·云计算·agent
2601_9622184717 小时前
万象生鲜系统多账套隔离技术适配集团生鲜企业集团化数字化管控
大数据·运维·微服务·云原生·架构