OpenFeign 快速开始

我们今天来学习 OpenFeign,我们将会搭建一个 order-openfeign 服务,通过 openfeign 调用 user 服务。

一、项目准备

Nacos 快速开始 的父项目基础上

1.1、从 order 模块复制出 order-openfeign 模块

1.2、修改 order-openfeign pom.xml artifactId

<artifactId>order-openfeign</artifactId>

1.3、修改父工程 pom.xml 

增加 order-openfeign 模块

<modules>
   <module>user</module>
   <module>order</module>
   <module>order-openfeign</module>
</modules>

二、Spring Cloud Alibaba 整合 OpenFeign

2.1、引入 openfeign 依赖

<!--openfeign 场景启动器 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!--openfeign 依赖 loadbalancer -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

2.2、编写接口加上 @FeignClient 注解

@FeignClient(value = "user-service", path = "/user")
public interface UserFeignService {

    @RequestMapping("/findUserById/{id}")
    String findUserById(@PathVariable("id") String id);

}
------------------------------------------------------
-- feign 接口可以参考被调用方的 controller
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/findUserById/{id}")
    public String findUserById(@PathVariable String id) {
        // 模拟从数据库获取用户
    }

}

注意:

  • @FeignClient 的 value 填的是被调用方的服务名,path 对应 @RequestMapping("/user")
  • Feign 接口的 @PathVariable 的 value 不能省略,否则会报 IllegalStateException

          PathVariable annotation was empty on param 0.

2.3、调用端添加 @EnableFeignClients 注解

有两种方式:

1)在启动类添加

@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}
  • 当你在 Spring Boot 项目中使用 @EnableFeignClients 注解时,默认情况下,Spring 会扫描标注了该注解的类所在的包及其子包中的所有 Feign 客户端。
  • 因此,如果你将 @EnableFeignClients 放在启动类上(通常是项目的根包),那么它会自动扫描整个项目中的 Feign 客户端。

2)显式指定要扫描的包路径

// 用 basePackages 显示指定
@Configuration
@EnableFeignClients(basePackages="com.study.order.feign")
public class FeignConfig {
}

2.4、像调用本地方式一样调用远程服务

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserFeignService userFeignService;

    @RequestMapping("/placeOrderFeign/{userId}")
    public String placeOrderFeign(@PathVariable String userId) {
        String response = userFeignService.findUserById(userId);
        return "用户[" + response + "]下单成功!";
    }
}

三、调用

启动 order-openfeign 模块跟两个 user 模块。

多次访问,会发现,用户服务在 8020、8021 之间来回切换。

从这能发现 OpenFeign 自动帮我们集成了 loadbalancer,实现负载均衡的调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值