1

OpenFeign3入门

 1 year ago
source link: https://blog.51cto.com/lianghecai/5749193
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

OpenFeign 是 Spring Cloud 家族的一个成员, 它最核心的作用是为 HTTP 形式的 Rest API 提供了非常简洁高效的 RPC 调用方式

第一步:添加依赖

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

第二步:编写调用接口

@ComponentScan
//name:指定调用Rest接口所对应的服务名
//path:指定要调用的Rest接口所在的项目的context-apth,如果Rest接口所在的项目有指定conext-path,则不用指定
@FeignClient(name = "nacos-payment",path = "/payment")
public interface PaymentFeignService {
    //声明Rest接口需要调用的方法
    @GetMapping("/nacos/{id}")
    String getPayment(@PathVariable("id") Integer id);
}

第三步:发起调用,像调用本地方式一样调用远程服务

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping("/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id) {
        return paymentFeignService.getPayment(id);
    }
}

第四步:在主启动类上添加@EnableFeignClients注解

@EnableFeignClients
@SpringBootApplication
public class Consumer9002Application {

    public static void main(String[] args) {
        SpringApplication.run(Consumer9002Application.class, args);
    }

}

第五步:运行测试


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK