一般来说就是接口+注解:微服务调用接口+@FeignClient
Feign在消费端使用
在项目中实践:
1、新建cloud-consumer-feign-order80
2、改POM
<!--openfeign--> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>com.sl.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>3、写YML
server: port: 80 eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka4、主启动类(@EnableFeignClients)
@SpringBootApplication @EnableFeignClients public class OrderFeignMain80 { public static void main(String[] args) { SpringApplication.run(OrderFeignMain80.class,args); } }5、业务类 ①新建PaymentFeignService接口并新增注解@FeignClient 这个Service里面的方法就是生产者的Controller里面的方法。 即Controller(consumer)—>Service(Feign)–>Controller(Provider)
@Component @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService { /** * 相当于在消费者Controller和生产者Controller中加了一层Service * * Controller(consumer)--->Service(Feign)-->Controller(Provider) * @param id * @return */ @GetMapping(value = "/payment/get/{id}") public CommonResult getPaymentById(@PathVariable("id") Long id); }②控制层Controller
@RestController public class OrderFeignController { @Resource private PaymentFeignService paymentFeignService; @GetMapping(value = "/consumer/payment/get/{id}") public CommonResult<payment> getPaymentById(@PathVariable("id") Long id){ return paymentFeignService.getPaymentById(id); } }6、测试
①先启动2个eureka集群7001/7002 ②再启动2个微服务8001/8002 ③启动OpenFeign80 ④http://localhost/consumer/payment/get/31
注意:Feign自带负载均衡配置项