从零开始学springboot整合feign跨服务调用的方法

2025-05-29 0 104

介绍

微服务横行的互联网世界, 跨服务调用显得很平凡, 我们除了采用传统的http方式接口调用, 有没有更为优雅方便的方法呢?

答案是肯定的,feign就提供了轻便的方式!

如果你的服务都注册了注册中心,比如nacos, 那么调用会显得很轻松, 只需一个注解, 带上需要调用的服务名即可,**feign + nacos**会帮你做剩余的事.

如果没有注册中心, 也无需担心, feign一样可以以传统的

ip:port

方式进行调用~

下面,我们来实践下吧

springboot整合feign

引入依赖, 这里注意, spring-cloud.version记得要和spring-boot版本匹配, 我这里spring-boot版本是2.1.3, 所以spring-cloud选择Greenwich.SR2版本.

大致的版本对应关系如下

从零开始学springboot整合feign跨服务调用的方法

更详细的请去https://start.spring.io/actuator/info
查询!

  1. <properties>
  2. <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
  3. </properties>
  4. <dependencyManagement>
  5. <dependencies>
  6. <!–SpringCloud依赖 –>
  7. <dependency>
  8. <groupId>org.springframework.cloud</groupId>
  9. <artifactId>spring-cloud-dependencies</artifactId>
  10. <version>${spring-cloud.version}</version>
  11. <type>pom</type>
  12. <scope>import</scope>
  13. </dependency>
  14. </dependencies>
  15. </dependencyManagement>
  16. <dependencies>
  17. <!–openfeign跨服务调用–>
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-starter-openfeign</artifactId>
  21. </dependency>
  22. <!–openfeign底层使用ApacheHttpClient调用–>
  23. <dependency>
  24. <groupId>io.github.openfeign</groupId>
  25. <artifactId>feign-httpclient</artifactId>
  26. </dependency>
  27. </dependencies>

然后我们去项目的启动类上加上注解
@EnableFeignClients

从零开始学springboot整合feign跨服务调用的方法

最后, 加上Feign的配置
application.properties

  1. server.port=9999
  2. #******************openfeign配置,参数采用的是默认的配置,可根据实际情况调整***********************
  3. #启用ApacheHttpClient。默认就是true,使用HttpClientConnectionManager管理连接复用
  4. feign.httpclient.enabled=true
  5. #连接池的最大连接数,默认200
  6. feign.httpclient.maxconnections=200
  7. #每个路由(服务器)分配的组最大连接数,默认50
  8. feign.httpclient.maxconnectionsperroute=50
  9. #连接最大存活时间,默认900秒
  10. feign.httpclient.timetolive=900
  11. #连接最大存活时间单位秒
  12. feign.httpclient.timetoliveunit=seconds
  13. #FeignAcceptGzipEncodingInterceptor拦截器被激活,会在header中添加Accept-Encoding:gzip,deflate,表明服务端在返回值时可以使用如下两个方式压缩返回结果
  14. feign.compression.response.enabled=true
  15. #FeignContentGzipEncodingInterceptor拦截器被激活,会在header中添加Content-Encoding:gzip,deflate,表明body中的参数是使用这两个方式的压缩
  16. feign.compression.request.enabled=true
  17. #content-length大于2048就进行请求参数的gzip压缩
  18. feign.compression.request.minRequestSize=2048
  19. #开启断路器
  20. feign.hystrix.enabled=true
  21. #断路器的隔离策略,默认就是线程池,SEMAPHORE模式下,就是主线程调用的远程的服务,即同步的
  22. hystrix.command.default.execution.isolation.strategy=THREAD
  23. #断路器超时设置
  24. hystrix.command.default.execution.timeout.enabled=true
  25. #总体请求在45秒还是无法得到响应,建议触发熔断(ribbon每个请求读取15秒超时,两个实例重试就是30秒,openfeign外层默认会进行一次调用,4次重试)
  26. hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=45000
  27. #断路器的线程池存在一个问题,在队列满了以后,不会再去创建新的线程直到maximumSize
  28. #核心线程池大小
  29. hystrix.threadpool.default.coreSize=10
  30. #最大线程池大小
  31. hystrix.threadpool.default.maximumSize=10
  32. #超过这个空闲时间,多于coreSize数量的线程会被回收,1分钟
  33. hystrix.threadpool.default.keepAliveTimeMinutes=1
  34. #队列的大小,默认为-1,即没有队列
  35. hystrix.threadpool.default.maxQueueSize=200
  36. #队列任务达到此阈值后,就开始拒绝;实际使用此参数进行队列是否满的判断
  37. hystrix.threadpool.default.queueSizeRejectionThreshold=180
  38. #负载均衡配置
  39. #读取超时15秒,与原RestTemplate保持一致
  40. ribbon.ReadTimeout=15000
  41. #连接超时15秒,与原RestTemplate保持一致
  42. ribbon.ConnectTimeout=15000
  43. ##每台服务器最多重试次数,但是首次调用不包括在内
  44. ribbon.MaxAutoRetries=0
  45. ##最多重试多少台服务器,与实际实例数保持一致(不包括首台)
  46. ribbon.MaxAutoRetriesNextServer=1
  47. #是否所有操作都重试,
  48. # false:get请求中,连接超时,读取超时都会重试,其他请求(put,post)连接超时重试,读取超时不重试。
  49. # true:get请求中,连接超时,读取超时都会重试,其他请求(put,post)连接超时重试,读取超时重试。
  50. #对于请求(put,post)要做好接口的幂等性
  51. ribbon.OkToRetryOnAllOperations=true

spring-boot整合feign完成, 接下来我们编写测试代码

测试代码

两个服务

  • sb-alibaba-nacos (被调用方服务, 127.0.0.1:8081), 提供 getInfoById接口
  • sb-feign (调用方服务, 127.0.0.1:9999), 提供 getInfoById 测试接口

sb-alibaba-nacos提供的测试接口

  1. @GetMapping(value = "getInfoById")
  2. public String getInfoById(@RequestParam(value = "id") Long Id) {
  3. return "example-service return :" + Id;
  4. }

sb-feign相关代码

我们新建个包 feign,用来放所有涉及跨服务调用的类

从零开始学springboot整合feign跨服务调用的方法

ExampleControllerFeignClient.java:

  1. package com.mrcoder.sbfeign.feign;
  2. import feign.hystrix.FallbackFactory;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.cloud.openfeign.FeignClient;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. @FeignClient(name = "sb-alibaba-nacos", url = "http://127.0.0.1:8081/", fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.class)
  10. public interface ExampleControllerFeignClient {
  11. @GetMapping(value = "getInfoById")
  12. String getInfoById(@RequestParam(value = "id") Long Id);
  13. /**
  14. * 服务降级内部类
  15. */
  16. @Component
  17. class ExampleControllerFeignClientFallbackFactory implements FallbackFactory<ExampleControllerFeignClient> {
  18. private Logger logger = LoggerFactory.getLogger(ExampleControllerFeignClientFallbackFactory.class);
  19. @Override
  20. public ExampleControllerFeignClient create(Throwable cause) {
  21. return new ExampleControllerFeignClient() {
  22. @Override
  23. public String getInfoById(Long signingLogId) {
  24. logger.error("跨服务调用失败, 原因是:" + cause.getMessage());
  25. return "失败, 原因是:" + cause.getMessage();
  26. }
  27. };
  28. }
  29. }
  30. }

关键代码就是

  1. @FeignClient(name = "sb-alibaba-nacos", url = "http://127.0.0.1:8081/", fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.class)
  • name 就是被调用方的服务名称 (这里如果你没有配置服务注册中心的化,其实可以随便写)
  • url 就是被调用方的地址(如果配置了服务注册中心, 可以不写!, 不过两个服务必须都注册!,这样才能找到!)
  • fallbackFactory 就是调用失败时指定的处理类

最后, 我们写个测试方法

  1. package com.mrcoder.sbfeign.controller;
  2. import com.mrcoder.sbfeign.feign.ExampleControllerFeignClient;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.*;
  5. @CrossOrigin
  6. @RestController
  7. public class TestController {
  8. @Autowired
  9. private ExampleControllerFeignClient exampleControllerFeignClient;
  10. @RequestMapping(value = "getInfoById", method = RequestMethod.GET)
  11. public String test(@RequestParam(value = "id") Long Id) {
  12. return exampleControllerFeignClient.getInfoById(Id);
  13. }
  14. }

开启两个服务sb-alibaba-nacos, sb-feign

而后访问sb-feign的测试方法

http://localhost:9999/getInfoById?id=22

出现

sb-alibaba-nacos return :22

跨服务调用成功~

到此这篇关于从零开始学springboot整合feign跨服务调用的文章就介绍到这了,更多相关springboot整合feign跨服务调用内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/mrcoderstack/article/details/109443790

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 从零开始学springboot整合feign跨服务调用的方法 https://www.kuaiidc.com/108387.html

相关文章

发表评论
暂无评论