springCloud搭建各種微服務之後,服務間通常存在相互調用的需求,springCloud提供了@FeignClient 註解非常優雅的解決了這個問題
首先,保證幾個服務在一個Eureka中形成服務場。如下,我一共有三個服務註冊在服務場中。
COMPUTE-SERVICE ; FEIGN-CONSUMER ; TEST-DEMO;
現在,我在FEIGN-CONSUMER 服務中調用其他兩個服務的兩個接口,分別爲get帶參和post不帶參兩個接口如下
這個是COMPUTE-SERVICE中的get帶參方法
@RequestMapping(value = "/add" ,method = RequestMethod.GET)
public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
ServiceInstance instance = client.getLocalServiceInstance();
Integer r = a + b;
logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
return r;
}
如果要在FEIGN-CONSUMER 服務中調用這個方法的話,需要在 FEIGN-CONSUMER 中新建一個接口類專門調用某一工程中的系列接口
@FeignClient("compute-service")
public interface ComputeClient {
@RequestMapping(method = RequestMethod.GET, value = "/add")
Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
}
其中,@FeignClient註解中標識出準備調用的是當前服務場中的哪個服務,這個服務名在目標服務中的
spring.application.name
這個屬性中取
接下來,在@RequestMapping中設置目標接口的接口類型、接口地址等屬性。然後在下面定義接口參數以及返回參數最後,在FEIGN-CONSUMER Controller層調用方法的時候,將上面接口注入進來,就可以直接用了
@Autowired
ComputeClient computeClient;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public Integer add() {
return computeClient.add(10, 20);
}
當然,post方法同理:
這是目標接口:
@RestController
@RequestMapping("/demo")
@EnableAutoConfiguration
public class HelloController {
@RequestMapping(value = "/test",method = RequestMethod.POST)
String test1(){
return "hello,test1()";
}
}
這是在本項目定義的接口文件:
@FeignClient("test-Demo")
public interface TestDemo {
@RequestMapping(method = RequestMethod.POST, value = "/demo/test")
String test();
}
這是本項目的Controller層:
@RestController
public class ConsumerController {
@Autowired
TestDemo testDemo;
@Autowired
ComputeClient computeClient;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public Integer add() {
return computeClient.add(10, 20);
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
return testDemo.test();
}
}
最終調用結果如下
OK 服務間接口調用就這樣了