组团学

Feign

阅读 (4354347)

1、认识Feign

1.1、Feign概述

Feign是一个声明式的Web Service客户端,它使编写Web Service客户端变得容易。Spring Cloud为Feign客户端添加了Spring MVC的注解支持,Feign在整合了Ribbon后可以提供负载均衡功能。

1.2、使用Feign调用服务

1.2.1、创建Spring Cloud应用,添加Feign、Eureka Discovery Client和Web依赖

1588917227212.png

1588917238111.png

1588917747987.png

1.2.2、编写配置

spring.application.name=open-feign
server.port=50006
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka01:50001/eureka/,http://eureka02:50002//eureka/

1.2.3、添加Feign支持

@SpringBootApplication @EnableDiscoveryClient //开启客户端发现 @EnableFeignClients //开启Feign支持 public class OpenFeignApplication { public static void main(String[] args) { SpringApplication.run(OpenFeignApplication.class, args); } }

1.2.4、实现Feign接口

@FeignClient(name = "provider") public interface FeignClients { @GetMapping("/hello") public String hello(); }

1.2.5、实现调用服务接口

@RestController public class HelloController { @Autowired FeignClients feignClients; @GetMapping("/hello") public String index(){ return feignClients.hello(); } }

1.2.6、启动"服务中心"、"服务提供者"和"Feign"工程

访问http://localhost:50006/hello

1588918461769.png

1588918450060.png

经验:

  • feignClient接口 有参数在参数必须加@PathVariable(“XXX”)和@RequestParam(“XXX”)

  • feignClient返回值为复杂对象时其类型必须有无参构造函数

需要 登录 才可以提问哦