当前位置: 首页 > article >正文

feign 远程调用详解

        在平常的开发工作中,我们经常需要跟其他系统交互,比如调用用户系统的用户信息接口、调用支付系统的支付接口等。那么,我们应该通过什么方式进行系统之间的交互呢?今天,简单来总结下 feign 的用法。

     1:引入依赖

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
     <version>版本根据自己业务需要选择</version>
</dependency>

      2:定义服务地址

# 服务名
mall:
  # 服务地址,如果有项目名称或者前置统一的url,建议配置在这儿
  url: http://localhost:8080  
  # 用户名 可选
  account: 
  # 密码 可选
  password: 

     3:启动类添加  @EnableFeignClients 注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
// 启用 Spring Cloud OpenFeign 客户端功能
@EnableFeignClients
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

      4:定义服务端接口

@RequiredArgsConstructor
@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * 查询信息
     */
    @GetMapping(value = "/info")
    public String getTestInfo() {
       return "666";
    }

}

      5:创建 feign 客户端接口

/**
 * 定义feign客户端接口
 */
@FeignClient(name = "mallFeignClient", url = "${mall.url}")
public interface MallFeignClient {

    /**
     * 查询信息

     * @return 信息
     */
    @GetMapping("/test/info")
    String queryTestInfo();

}

      6:使用 feign 调用远程 mall 服务接口

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
@Slf4j
public class TestController {

    // fegin定义的接口客户端
    private final MallFeignClient mall;

    /**
     * 客户端controller
     *
     * @return 信息
     */
    @GetMapping("/msg")
    public String queryInfo() {
        return mall.queryTestInfo();
    }

}

     7:测试

        调用当前服务 /test/msg 接口,返回 mall 服务 /test/info 接口的返回值

        ​​​​​​ 

        以上为 feign 调用的基本过程,客户端根据服务地址和接口信息调用服务端的接口。feign 是声明式编程,类似于本地方法调用,极大简化系统之间调用的步骤,便于开发和维护。结合 Ribbon 等负载均衡组件,Feign 可以实现客户端负载均衡。


http://www.kler.cn/a/536080.html

相关文章:

  • 杭州某小厂面试
  • 机器学习数学基础:14.矩阵的公式
  • MySQL第四次实验
  • 初窥强大,AI识别技术实现图像转文字(OCR技术)
  • Copilot量化指标参数及其方法
  • leetcode_78子集
  • python编程-内置函数bin(),bool(),abs() ,all(),any(),ascii(),max(),min() 详解
  • 【AIGC提示词系统】基于 DeepSeek R1 + Claude AI占卜师:探索生活预测的新方式
  • GitHub Copilot:智能助手觉醒
  • 攻防世界ctf
  • 深入浅出深度优先搜索(DFS)——以经典N皇后问题为例
  • 探索元宇宙:Facebook 如何重塑社交生态
  • A Comprehensive Study on Text-attributed Graphs: Benchmarking and Rethinking
  • 第3章《VTK可视化基础》
  • 蓝桥杯准备 【入门3】循环结构
  • Axure大屏可视化动态交互设计:解锁数据魅力,引领决策新风尚
  • 代码随想录day30
  • 行测智能组卷【61分】
  • ctf网络安全题库 ctf网络安全大赛答案
  • 基于微信小程序的医院预约挂号系统的设计与实现
  • 如何下载B站视频到本地
  • docker,k8s,docker compose三者的关系
  • Kafka 入门与实战
  • (2025,推理语言模型 / RLM,deepseek-v3,推理结构,推理策略,强化学习概念,监督学习方法,计算优化技术)
  • OBS::Display
  • GlusterFS源码讲解:如何实现最终一致性