OpenFeign 声明式实现 调用业务api

1、引入依赖

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

注意:也要引用负载均衡的依赖

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

2、启动类添加注解,开启Feign远程调用功能

@EnableFeignClients

3、创建FeignClient

feign.ProductFeignClient

4、添加注解,通过微服务名指定远程调用的微服务地址 http:// ip + port

@FeignClient("services-product")

5、定义方法

语法

指定远程地址:@FeignClient // 服务名
指定请求方式:@GetMapping、@PostMapping、@DeleteMapping 
指定携带数据:@RequestHeader、@RequestParm、@RequestBody...
指定返回结果:响应模型

案例

@FeignClient("services-product")
public interface ProductFeignClient {
    @GetMapping("product/{id}")
    Product getProductById(@PathVariable Long id);
}

6、使用(当组件使用)

@Autowired
private ProductFeignClient productFeignClient;

 

posted @ 2025-06-08 22:06  市丸银  阅读(12)  评论(0)    收藏  举报