轉自:https://www.cnblogs.com/zhaosq/archive/2019/10/28/11675639.html
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 服務間接口調用就是這樣了!
SpringCloud 服務間互相調用 @FeignClient注解