SpringCloud OpenFeign概述与使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringCloud OpenFeign概述与使用

情绪大瓜皮丶   2023-02-03 我要评论

OpenFeign概述

OpenFeign 可以声明式的实现微服务之间的调用,我们只需要向调用接口一样,对 FeignClient 直接调用即可。

若不采用 OpenFeign,不同微服务之间的远程 API 调用通过Ribbon + RestTemplate实现;而采用 OpenFeign 后直接采用接口 + 注解的方式即可实现。

OpenFeign使用

本文仍然使用SpringCloud – Nacos中所创建的 order 订单微服务与 payment 支付微服务为例,在订单微服务中调用支付微服务的方法。

引入依赖

首先在 order 微服务中引入 OpenFeign 的依赖

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

编写服务调用Service接口

创建 Service 接口,在接口中定义方法实现对其他微服务的调用

注意:

  • @FeignClient括号里的值为被调用的微服务在 nacos 注册中心的注册服务名;
  • 定义的方法上的请求及路径需要与被调用服务的相应方法匹配;
@FeignClient("nacos-payment-provider")
public interface PaymentService {
    /**
     * 测试调用Payment
     * @return 调用结果
     */
    @GetMapping("/paymentFeign/test")
    String feignTest();
}

编写被调用的方法

在两个被调用的 payment 服务中编写业务处理逻辑,此处为方便,直接返回相应的字符串

paymeng8001

@RestController
@RequestMapping("/paymentFeign")
public class PaymentFeignController8001 {
    @GetMapping("/test")
    public String test() {
        return "8001支付模块test()方法被调用~";
    }
}

payment8002

@RestController
@RequestMapping("/paymentFeign")
public class PaymentFeignController8002 {
    @GetMapping("/test")
    public String test() {
        return "8002支付模块test()方法被调用~";
    }
}

支付模块修改完成后,直接启动服务

启动服务调用模块

在 order8005 模块的启动类上添加注解,标明 FeignClient 包的位置

@SpringBootApplication
@EnableFeignClients(basePackages = "com.zqf.service")
public class OrderStart8005 {
    public static void main(String[] args) {
        SpringApplication.run(OrderStart8005.class);
    }
}

启动订单微服务

测试

所有微服务启动成功后,使用 postman 进行测试

多次发送请求,可以看到两个支付微服务 payment 被轮流调用,即 openfeign 自带负载均衡的功能行测试

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们