zoukankan      html  css  js  c++  java
  • 微服务 通过EnableFeignClients调用其他服务的api

    今天在项目上遇到一个问题,通过当前service服务要调用到其他service服务的api接口时,可通过EnableFeignClients调用其他服务的api,大概的步骤如下:

    1、在springboot的main处加上注解@EnableFeignClients

     1 @EnableDiscoveryClient
     2 @SpringBootApplication
     3 @EnableFeignClients
     4 public class MyServiceApplication {
     5 
     6     public static void main(String[] args){
     7         SpringApplication.run(MyServiceApplication.class, args);
     8     }
     9 
    10 }

    2、在service层上实现接口,这里注意value可以用serviceId代替,但是最好用value来指定要调用的服务。

          fallback是当程序错误的时候来回调的方法

          方法中要用@PathVariable要注解参数

    1 @FeignClient(value = "other-service", fallback = ExampleFeignClientFallback.class)
    2 public interface ExampleFeignClient {
    3     @RequestMapping(value = "/v1/exampleId/{id}",method = RequestMethod.GET)
    4     Long queryById(@PathVariable(name="id") Long id);
    5 }


    3、编写程序错误时的回调类,实现接口,在错误时回调

    1 @Service
    2 public class ExampleFeignClientFallback implements ExampleFeignClient {
    3     @Override
    4     public Long queryById(Long id) {
    5         return null;
    6     }
    7 }


    4、调用该服务

    1 //声明,自动封装
    2 @Autowired
    3 private ExampleFeignClient ExampleFeignClient;
    4 
    5 
    6 //调用
    7 Long result = ExampleFeignClient.queryById(id);

    至此,完成整个步骤

  • 相关阅读:
    洛谷—— P3353 在你窗外闪耀的星星
    洛谷—— P1238 走迷宫
    洛谷—— P1262 间谍网络
    9.8——模拟赛
    洛谷—— P1189 SEARCH
    算法
    May 22nd 2017 Week 21st Monday
    May 21st 2017 Week 21st Sunday
    May 20th 2017 Week 20th Saturday
    May 19th 2017 Week 20th Friday
  • 原文地址:https://www.cnblogs.com/UniqueColor/p/7130782.html
Copyright © 2011-2022 走看看