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)
2public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
3    ServiceInstance instance = LocalServiceInstance();
4    Integer r = a + b;
5    logger.info("/add, host:" + Host() + ", service_id:" + ServiceId() + ", result:" + r);
6return r;
7 }
如果要在FEIGN-CONSUMER 服务中调⽤这个⽅法的话,需要在 FEIGN-CONSUMER 中新建⼀个接⼝
类专门调⽤某⼀⼯程中的系列接⼝1 @FeignClient("compute-service")
2public interface ComputeClient {
3
4    @RequestMapping(method = RequestMethod.GET, value = "/add")
5    Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);springcloud怎么读音
6
7 }
其中,@FeignClient注解中标识出准备调⽤的是当前服务场中的哪个服务,这个服务名在⽬标服务中的配置中取
1spring.application.name
接下来,在@RequestMapping中设置⽬标接⼝的接⼝类型、接⼝地址等属性。然后在下⾯定义接⼝参数以及返回参数
最后,在FEIGN-CONSUMER Controller层调⽤⽅法的时候,将上⾯接⼝注⼊进来,就可以直接⽤了
1 @Autowired
2 ComputeClient computeClient;
3
4 @RequestMapping(value = "/add", method = RequestMethod.GET)
5public Integer add() {
6return computeClient.add(10, 20);
7 }
当然,post⽅法同理:
这是⽬标接⼝:
1 @RestController
2 @RequestMapping("/demo")
3 @EnableAutoConfiguration
4public class HelloController {
5    @RequestMapping(value = "/test",method = RequestMethod.POST)
6    String test1(){
7return "hello,test1()";
8    }
9 }
这是在本项⽬定义的接⼝⽂件:
1 @FeignClient("test-Demo")
2public interface TestDemo {
3    @RequestMapping(method = RequestMethod.POST, value = "/demo/test")
4    String test();
5 }
这是项⽬中的Controller层:
1 @RestController
2public class ConsumerController {
3    @Autowired
4    TestDemo testDemo;
5
6    @Autowired
7    ComputeClient computeClient;
8
9    @RequestMapping(value = "/add", method = RequestMethod.GET) 10public Integer add() {
11return computeClient.add(10, 20);
12    }
13
14    @RequestMapping(value = "/test", method = RequestMethod.GET) 15public String test() {
st();
17    }
18 }
最终调⽤结果如下:
OK 服务间接⼝调⽤就是这样了!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。