Spring Cloud 服务间调用 @FeignClient 注解

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()";
   }
}

这是在本项目定义的接口文件:

扫描二维码关注公众号,回复: 1109283 查看本文章

@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 服务间接口调用就这样了

猜你喜欢

转载自blog.csdn.net/qq_29884151/article/details/80492264