微服务 通过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);

 

至此,完成整个步骤

 

posted @ 2017-07-07 10:25  UniqueColor  阅读(51242)  评论(0编辑  收藏  举报