Feign
Feign的作用
Feign可以帮助我们实现面向接口编程,就直接调用其他的服务,简化开发。
Feign的快速入门
导入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
添加一个注解
- @EnableFeignClients
创建一个接口,并且和Search模块做映射@FeignClient("SEARCH") // 指定服务名称 public interface SearchClient { // value -> 目标服务的请求路径,method -> 映射请求方式 @RequestMapping(value = "/search",method = RequestMethod.GET) String search(); }
测试使用
@Autowired private SearchClient searchClient; @GetMapping("/customer") public String customer(){ String result = searchClient.search(); return result; }
Feign的传递参数方式
注意事项
- 如果你传递的参数,比较复杂时,默认会采用POST的请求方式。
- 传递单个参数时,推荐使用@PathVariable,如果传递的单个参数比较多,这里也可以采用@RequestParam,不要省略value属性
- 传递对象信息时,统一采用json的方式,添加@RequestBody
- Client接口必须采用@RequestMapping
在Search模块下准备三个接口
@GetMapping("/search/{id}")路径传参时,一定要添加@PathVariable public Customer findById(@PathVariable Integer id){ return new Customer(1,"张三",23); } @GetMapping("/getCustomer")// 单个参数一定要添加@RequestParam public Customer getCustomer(@RequestParam Integer id,@RequestParam String name){ return new Customer(id,name,23); } @PostMapping("/save") public Customer save(@RequestBody Customer customer){ return customer; }
封装Customer模块下的Controller
@GetMapping("/customer/{id}") public Customer findById(@PathVariable Integer id){ return searchClient.findById(id); } @GetMapping("/getCustomer") public Customer getCustomer(@RequestParam Integer id, @RequestParam String name){ return searchClient.getCustomer(id,name); } @GetMapping("/save") // 会自动转换为POST请求 public Customer save(Customer customer){ return searchClient.save(customer); }
再封装Client接口
@RequestMapping(value = "/search/{id}",method = RequestMethod.GET) Customer findById(@PathVariable(value = "id") Integer id); @RequestMapping(value = "/getCustomer",method = RequestMethod.GET) Customer getCustomer(@RequestParam(value = "id") Integer id, @RequestParam(value = "name") String name); @RequestMapping(value = "/save",method = RequestMethod.POST) Customer save(@RequestBody Customer customer);
Feign的FallBack、FallBackFactory
Fallback可以在其他服务出现异常时,返回托底数据,避免程序出现异常信息。
FallbackFactory可以在Fallback的基础上,获取到其他服务发生的异常信息。
- 创建POJO类,实现client接口,并重写方法即可,方法返回的结果就时托底数据。Fallback对象
- 添加配置文件:
feign: hystrix: enabled: true
创建POJO类,实现FallbackFactory<Client接口>接口,重写create方法,返回Fallback对象