SpringCloud-基于Feign远程调用

news/2024/7/10 2:43:34 标签: spring cloud, java, 后端, 分布式, 微服务, 负载均衡, feign

Spring Cloud 是一个用于构建分布式系统的开发工具包,它提供了一系列的微服务组件,其中之一就是 Feign。Feign 是一种声明式的 Web 服务客户端,它简化了在 Spring Cloud 中进行远程调用的过程。本文将介绍如何在 Spring Cloud 中使用 Feign 进行远程调用。


一、引入Feign依赖

我们在 Spring Cloud 项目的 pom.xml 中,添加 Feign 的依赖。

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


二、定义和使用Feign客户端

在远程调用的服务模块中,创建一个 Feign 客户端接口

java">package com.example.eurekaconsumer.demos.web;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient ("userseryice")
public interface UserClient {
    @GetMapping("/user/{name}")
    User findById(@PathVariable("name") String name);
}

这个接口使用了 Spring MVC 的注解,定义了远程服务的调用方式。  


三、启动类开启Feign客户端

启动类添加 @EnableFeignClients 注解:

java">package com.example.eurekaconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class EurekaConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumerApplication.class, args);
    }

}


四、调用FeignClient接口

在需要应用的模块中,注入 Feign 客户端接口并使用它来进行远程调用。

java">package com.example.eurekaconsumer.demos.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserClient userClient;

    @RequestMapping("/showUser")
    @ResponseBody
    public User showUser() {
        User userInfo = userClient.findByName("Damon");
        return userInfo;
    }

}

可以看到,使用 Feign 调用的方法非常优雅,可维护性也很强。


五、FeignClient应用实例

1、实现负载均衡

我们可以用 FeignClient 代替 RestTemplate 以实现负载均衡

我们先看下参考原有的 RestTemplate 实现负载均衡的代码:

java">package com.example.eurekaconsumer.demos.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/showUser")
    @ResponseBody
    public User showUser() {
        String baseUrl = "http://" + "eureka-provider" + "/user";
        User userInfo = restTemplate.getForObject(baseUrl, User.class);
        return userInfo;
    }

}

可以看到我们用 RestTemplate 实现负载均衡时,遇到没有参数传递的情况还是比较方便的,但是遇到形如 url?param1=xxx&param2=xxx&param3=xxx&param4=xxx 的应用场景时就需要重构代码,非常的不方便。

于是我们使用自带负载均衡的 Feign 远程调用方法,改造后的方法如下:

java">package com.example.eurekaconsumer.demos.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserClient userClient;

    @RequestMapping("/showUser")
    @ResponseBody
    public User showUser() {
        User userInfo = userClient.findByName("Damon");
        return userInfo;
    }

}

以上是一个简单的 Spring Cloud 中基于 Feign 的远程调用的示例。通过使用 Feign,你可以以声明式的方式定义远程服务调用,而无需手动处理 HTTP 请求和响应。这提高了代码的可读性和维护性,使远程调用更加方便。 

Feign 替换 RestTemplate 的好处: 

优势详细内容
声明式
API 定义
使用Feign时,你可以通过简单的注解方式声明HTTP请求,而不需要手动构建请求和处理响应。Feign的注解功能使得定义和维护API变得更加直观和容易。
集成了
负载均衡
在Spring Cloud环境中,Feign与Eureka或其他服务发现组件集成,可以自动进行负载均衡。你只需通过@FeignClient注解指定服务名,Feign就会在调用时自动帮你选择可用的服务实例。
支持多种编码
器和解码器
Feign支持多种编码器和解码器,包括JacksonGson等,这使得处理不同的数据格式变得更加灵活。
支持
内置断路器
Feign内置了断路器(Circuit Breaker)的支持,例如通过Hystrix。这使得在远程调用失败或超时时,可以采取快速失败和降级的策略,提高系统的稳定性和可靠性。
更易扩展Feign的设计使得它更易于扩展和自定义。你可以通过实现RequestInterceptor接口来添加自定义的请求拦截器,或者通过实现ErrorDecoder接口来处理自定义的错误解码逻辑。
简化了
配置和使用
Feign的默认配置较为智能,使得在大多数情况下你无需进行额外的配置就能够正常工作。相比之下,RestTemplate通常需要手动配置。

2、 实现多参数调用

当使用 FeignClient 进行远程调用时,有时我们需要传递多个参数给目标服务。使用 Feign 的多参数远程调用能够使代码更加优雅,避免了手动拼接 URL 或请求参数的繁琐工作。

以下是一个关于 FeignClient 多参数远程调用的应用实例:

① 创建FeignClient接口

首先,定义一个FeignClient接口,使用 @FeignClient 注解标记目标服务的名称。在接口中定义多个参数的远程调用方法。

java">import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "test-service")
public interface TestClient {

    @GetMapping("/api/test")
    String getResource(@RequestParam("param1") String param1,
                       @RequestParam("param2") int param2,
                       @RequestParam("param3") boolean param3);
}

在上述例子中,getResource 方法接收多个参数,分别使用 @RequestParam 注解进行标记。

② 基于FeignClient多参数调用

注入 FeignClient 接口并使用它进行多参数的远程调用。

java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestClient testClient;

    @GetMapping("/test")
    public String test(@RequestParam("param1") String param1,
                             @RequestParam("param2") int param2,
                             @RequestParam("param3") boolean param3) {
        // 调用远程服务并传递多个参数
        String result = testClient.getResource(param1, param2, param3);
        return "Result from test service: " + result;
    }
}

在这个例子中,TestController 的 test 方法接收多个参数,然后使用注入的 TestClient 进行远程调用,并传递这些参数。

通过使用 Feign 的方式,我们可以更加优雅地进行多参数的远程调用,避免了手动拼接URL或构建复杂的请求体。Feign 会自动将参数转化为请求参数,使得代码更加清晰、简洁。这种方式也符合 Spring Cloud 中微服务架构的设计理念,提高了代码的可读性和可维护性。


http://www.niftyadmin.cn/n/5382948.html

相关文章

MR混合现实情景实训教学系统在军事专业课堂上的应用

MR混合现实在军事专业课堂中的应用 1. 模拟实战环境&#xff1a;通过MR系统&#xff0c;教师可以模拟各种实战环境&#xff0c;让学生在实际操作中学习和掌握军事技能。例如&#xff0c;在战术训练中&#xff0c;学生可以在模拟的敌方阵地环境中进行实战演练&#xff0c;提高应…

【工具类】开源照片管理工具pthtoprism

1. pthtoprism 1. pthtoprism 1.1. 安装1.2. 管理照片方式 1.2.1. 直接管理原始照片目录1.2.2. 导入照片 1.3. 界面功能1.4. 参考资料 1.1. 安装 wget https://dl.photoprism.app/docker/docker-compose.yml # 修改 docker-compose.yml 文件&#xff0c;具体参考下面内容 d…

【4.1计算机网络】TCP-IP协议簇

目录 1.OSI七层模型2.常见协议及默认端口3.TCP与UDP的区别 1.OSI七层模型 osi七层模型&#xff1a; 1.应用层 2.表示层 3.会话层 4.传输层&#xff1a;TCP为可靠的传输层协议。 5.网络层 6.数据链路层 7.物理层 2.常见协议及默认端口 3.TCP与UDP的区别 例题1. 解析&#xff1…

自动化上位机开发C#100例:如何用面向对象的方式封装雷赛运动控制卡EtherCAT总线卡(C#代码)

自动化上位机开发C#100例:雷赛运动控制卡EtherCAT总线卡C#封装类 文章目录 LTDMC.dll下载LTDMC.cs LTDMC.dll C#调用封装下载ICard.cs 运动控制卡接口Card.cs 运动控制卡抽象类CardLTDMC.cs 雷赛运动控制卡EtherCAT总线卡实现类CardList.cs 总线卡列表封装 LTDMC.dll下载 最新…

关于react用脚手架搭建初始化后render渲染了两次的问题

问题&#xff1a;页面初始化的时候走了两次render渲染 入口文件 main.tsx 原因&#xff1a; react脚手架创建项目&#xff0c;默认会开启严格模式&#xff0c;在严格模式下&#xff0c;React 的开发环境会刻意执行两次渲染 解决方案&#xff1a;删掉严格模式的标签

Python Selenium实现自动化测试及Chrome驱动使用

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站零基础入门的AI学习网站~。 目录 ​编辑 前言 Selenium简介 安装Selenium库 编写自动化测试脚本 1 打开浏览器并访问网页 2 查找页面元…

Android新特性

Android 14 适配 1、targetSdkVersion 必须大于等于23&#xff08;Android 6.0&#xff09; 2、声明前台服务必须指定类型 3、动态注册广播要指定是否可以被导出 4、读取视频或图片增加了一个只允许访问部分图片或视频的权限&#xff08;强制&#xff09; 5、动态加载的文件&am…

算法-矩阵置零

1、题目来源 73. 矩阵置零 - 力扣&#xff08;LeetCode&#xff09; 2、题目描述 给定一个 m x n 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,1,1],[1,0,1…