天天看點

SpringCloud 服務間互相調用 @FeignClient注解

SpringCloud搭建各種微服務之後,服務間通常存在互相調用的需求,SpringCloud提供了@FeignClient 注解非常優雅的解決了這個問題

首先,保證幾個服務都在一個Eureka中注冊成功形成服務場。

如下,我一共有三個服務注冊在服務場中。COMPUTE-SERVICE ; FEIGN-CONSUMER ; TEST-DEMO;

現在,我在FEIGN-CONSUMER 服務中調用其他兩個服務的兩個接口,分别為get帶參和post不帶參兩個接口如下

這個是COMPUTE-SERVICE中的get帶參方法

1 @RequestMapping(value = "/add" ,method = RequestMethod.GET)
2 public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
3     ServiceInstance instance = client.getLocalServiceInstance();
4     Integer r = a + b;
5     logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
6     return r;
7 }      

如果要在FEIGN-CONSUMER 服務中調用這個方法的話,需要在 FEIGN-CONSUMER 中建立一個接口類專門調用某一工程中的系列接口

1 @FeignClient("compute-service")
2 public interface ComputeClient {
3 
4     @RequestMapping(method = RequestMethod.GET, value = "/add")
5     Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
6 
7 }      

其中,@FeignClient注解中辨別出準備調用的是目前服務場中的哪個服務,這個服務名在目标服務中的配置中取

1 spring.application.name      

接下來,在@RequestMapping中設定目标接口的接口類型、接口位址等屬性。然後在下面定義接口參數以及傳回參數

最後,在FEIGN-CONSUMER Controller層調用方法的時候,将上面接口注入進來,就可以直接用了
1 @Autowired
2 ComputeClient computeClient;
3 
4 @RequestMapping(value = "/add", method = RequestMethod.GET)
5 public Integer add() {
6     return computeClient.add(10, 20);
7 }      

當然,post方法同理:

這是目标接口:

1 @RestController
2 @RequestMapping("/demo")
3 @EnableAutoConfiguration
4 public class HelloController {
5    @RequestMapping(value = "/test",method = RequestMethod.POST)
6    String test1(){
7       return "hello,test1()";
8    }
9 }      

這是在本項目定義的接口檔案:

1 @FeignClient("test-Demo")
2 public interface TestDemo {
3     @RequestMapping(method = RequestMethod.POST, value = "/demo/test")
4     String test();
5 }      
這是項目中的Controller層:
1 @RestController
 2 public class ConsumerController {
 3     @Autowired
 4     TestDemo testDemo;
 5 
 6     @Autowired
 7     ComputeClient computeClient;
 8 
 9     @RequestMapping(value = "/add", method = RequestMethod.GET)
10     public Integer add() {
11         return computeClient.add(10, 20);
12     }
13 
14     @RequestMapping(value = "/test", method = RequestMethod.GET)
15     public String test() {
16         return testDemo.test();
17     }
18 }      

最終調用結果如下:

OK 服務間接口調用就是這樣了!