SpringCloud-基于Feign远程调用

这篇具有很好参考价值的文章主要介绍了SpringCloud-基于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>

SpringCloud-基于Feign远程调用,Java,spring cloud,java,后端,分布式,微服务,负载均衡,feign


二、定义和使用Feign客户端

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

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);
}

SpringCloud-基于Feign远程调用,Java,spring cloud,java,后端,分布式,微服务,负载均衡,feign

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


三、启动类开启Feign客户端

启动类添加 @EnableFeignClients 注解:

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);
    }

}

SpringCloud-基于Feign远程调用,Java,spring cloud,java,后端,分布式,微服务,负载均衡,feign


四、调用FeignClient接口

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

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 调用的方法非常优雅,可维护性也很强。

SpringCloud-基于Feign远程调用,Java,spring cloud,java,后端,分布式,微服务,负载均衡,feign


五、FeignClient应用实例

1、实现负载均衡

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

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

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 远程调用方法,改造后的方法如下:

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 注解标记目标服务的名称。在接口中定义多个参数的远程调用方法。

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 接口并使用它进行多参数的远程调用。

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 中微服务架构的设计理念,提高了代码的可读性和可维护性。文章来源地址https://www.toymoban.com/news/detail-832742.html

到了这里,关于SpringCloud-基于Feign远程调用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【spring Cloud】微服务通信的三种方式RestTemplate、Feign远程调用与Dubbo的使用

    目录 一、通过RestTemplate调用微服务 二、通过Feign远程调用 三、Dubbo  分布式中的远程调用大概分为两种 RESTful接口  REST,即Representational State Transfer的缩写,如果一个架构符合REST原则,就称它为RESTful架构。 每一个URI代表一种资源; 客户端和服务器之间,传递这种资源的某种

    2024年04月11日
    浏览(35)
  • SpringCloud --- Feign远程调用

    先来看我们以前利用RestTemplate发起远程调用的代码: 存在下面的问题: 代码可读性差,编程体验不统一 参数复杂URL难以维护 Feign是一个声明式的http客户端,官方地址:GitHub - OpenFeign/feign: Feign makes writing java http clients easier 其作用就是帮助我们优雅的实现http请求的发送,解决

    2024年02月05日
    浏览(32)
  • SpringCloud(七) Feign远程调用

    目录 一, RestTemplate远程调用存在的问题 二, Feign的远程调用 2.1 什么是Fegin 2.2 Feign的使用(代替RestTemplate) 1. 引入依赖 2. 添加注解  3. 编写Feign的客户端 4. 测试 5. 总结  2.3 自定义配置 1. 配置文件方式  2. Java代码方式  三, Feign使用优化 3.1 使用连接池 1. 引入依赖 2. 配置连接池

    2024年02月06日
    浏览(28)
  • SpringCLoud——Feign的远程调用

    来看一下之前我们使用RestTemplate调用时编写的Contrriller代码: //        2. 利用RestTemplate发起HTTP请求 //        2.1 url 地址         String url = \\\"http://userserver/user/\\\" + order.getUserId(); //        2.2 发送http请求,实现远程调用         User user = restTemplate.getForObject(url,

    2024年02月07日
    浏览(26)
  • 【微服务】SpringCloud之Feign远程调用

    🏡浩泽学编程 :个人主页  🔥 推荐专栏 :《深入浅出SpringBoot》《java对AI的调用开发》               《RabbitMQ》《Spring》《SpringMVC》《项目实战》 🛸学无止境,不骄不躁,知行合一 使用Feign远程调用代替RestTemplate远程调用。 使用RestTemplate发起远程调用: 虽然在引

    2024年04月15日
    浏览(23)
  • SpringCloud 核心组件Feign【远程调用&自定义配置】

    目录 1,Feign远程调用 1.1:Feign概述 1.2:Feign替代RestTemplate         1):引入依赖         2):添加注解         3):编写Feign的消费服务,提供服务         4):测试         5):总结 1.3:自定义配置 1.3.1:配置文件方式 1.3.2:Java代码方式 Feign是一款Java语言编写的

    2023年04月08日
    浏览(65)
  • 39.SpringCloud—配置管理nacos、远程调用Feign、服务网关Gateway

    目录 一、SpringCloud。 (1)Nacos配置管理。 (1.1)nacos中添加配置文件、微服务引入依赖,并配置bootstrap.yml文件。 (1.2)获取配置文件信息,实现热更新。 (1.3)多环境配置共享。 (1.4)多服务共享配置。 (2)http客户端Feign。 (2.1)RestTemplate方式调用存在的问题。 (2.2)

    2024年02月10日
    浏览(58)
  • SpringCloud实用篇2——Nacos配置管理 Feign远程调用 Gateway服务网关

    Nacos除了可以做注册中心,同样可以做配置管理来使用。 当微服务部署的实例越来越多,达到数十、数百时,逐个修改微服务配置就会让人抓狂,而且很容易出错。我们需要一种统一配置管理方案,可以集中管理所有实例的配置。 Nacos一方面可以将配置集中管理,另一方可以

    2024年02月13日
    浏览(36)
  • Spring Cloud Gateway如何优雅地进行feign调用

    之前写过一篇文章,介绍微服务场景下的权限处理,方案如下: 在实践中,上面的网关选型为Spring Cloud Gateway,所以这里就存在一个问题,即网关如何调用用户服务进行鉴权的问题。 在微服务场景下,服务间的调用可以通过feign的方式,但这里的问题是,网关是reactor模式,即

    2024年02月08日
    浏览(35)
  • 【java】Spring Cloud --Feign Client超时时间配置以及单独给某接口设置超时时间方法

    FeignClient面对服务级有三种超时时间配置 feign配置是在ribbon配置的基础上做了扩展,可以支持服务级超时时间配置,所以,feign配置和ribbon配置的效果应该是一样的。 SpringCloud对这两种配置的优先级顺序如下: Feign局部配置 Feign全局配置 Ribbon局部配置 Ribbon全局配置 在feign-co

    2024年02月12日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包