本文主要介绍如何在springcloud中通过openFeign实现微服务接口远程调用。本例使用的springcloud版本为:2021.0.3,springboot版本为:2.6.8。
打开idea新建项目,选择maven,创建springboot项目consumer-openfeign-order。
在项目pom中引入如下依赖:
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
-
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
- dependencies>
在项目resources文件夹下创建application.yml文件,并按如下内容进行配置:
- server:
- port: 80
-
- eureka:
- client:
- service-url:
- defaultZone: http://localhost:7001/eureka
- fetch-registry: true
- instance:
- instance-id: consumer-openfeign-order-${server.port}
- prefer-ip-address: true
-
- spring:
- application:
- name: consume-openfeign-order
在项目src/main/java下创建主应用类 ConsumerOpenFeignOrderApplication.java,添加注解@EnableEurekaServer、@SpringBootApplication、@EnableFeignClients。
- @EnableEurekaClient
- @SpringBootApplication
- @EnableFeignClients
- public class ConsumerOpenfeignOrderApplication {
- public static void main(String[] args) {
- SpringApplication.run(ConsumerOpenfeignOrderApplication.class, args);
- }
- }
在项目src/main/java/service下创建远程微服务接口类PaymentClientService,其中PAYMENT-SERVER为支付服务的服务名称。
- @FeignClient(name = "PAYMENT-SERVER")
- public interface PaymentClientService {
- @GetMapping("/payment/get/{id}")
- CommentResult
getById(@PathVariable(name = "id") Long id); - }
在controller层可以通过PaymentClientService进行远程微服务接口调用,使用方法如下:
- @RestController
- @RequestMapping("/order")
- public class OrderController {
- @Resource
- private PaymentClientService paymentClientService;
-
- @GetMapping("/get/{id}")
- CommentResult
getById(@PathVariable(name = "id") Long id) { - return paymentClientService.getById(id);
- }
- }
同时启动并运行项目eueka-server-7001、eueka-server-7002、payment-8001、payment-8002、consumer-openfeign-order。然后在postman中进行接口调用测试:
新时代农民工 (QQ:277718357) 点击关注下方↓微信公众号:程序进阶之路,实时获取更多技术文章推送。