架构:

引入依赖:
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
yml配置;
- server:
- port: 80
-
- spring:
- application:
- name: cloud-consumer-openfeign-order
- ####Spring Cloud Consul for Service Discovery
- cloud:
- consul:
- host: localhost
- port: 8500
- discovery:
- prefer-ip-address: true #优先使用服务ip进行注册
- service-name: ${spring.application.name}
-
- package com.wen.cloud.apis;
-
- import com.wen.cloud.entities.Pay;
- import com.wen.cloud.resp.ResultData;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestBody;
-
- @FeignClient(value = "cloud-payment-service")//对应注册中心的模块命名
- public interface PayFeignApi {
- @PostMapping(value = "/pay/add")
- public ResultData addPay(@RequestBody Pay pay);
-
- @GetMapping(value = "/pay/get/{id}")
- public ResultData getById(@PathVariable("id") Integer id);
-
- @GetMapping("/pay/getInfo")
- public String getInfoByConsul();
- }
cloud-payment-service中的方法体与PayFeignApi的对应关系:

将cloud-consumer-feign-order模块启动类添加注释,用于开启@FeignClient(value = "cloud-payment-service")注解


consumer中的orderController会自动装配PayFeignApi接口,并调用接口中提供的方法。该接口会通过@FeignClient(value = "cloud-payment-service")中的value名取注册中心寻找对应的微服务模块,并匹配该模块方法的路径并调用。

