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

  • 相关阅读:
    月亮的背后
    2007经典妙语100句
    2007经典妙语100句
    VS C++ 2005的预生成事件及设置
    user case VS. user story
    如何用正确的方法来写出质量好的软件的75条体会
    用 Lucene 加速 Web 搜索应用程序的开发
    巾帼不让须眉——女生做运维 interesting topic
    ebean
    Download the 2.0.0 Release of the Scala IDE for Eclipse Scala IDE for Eclipse
  • 原文地址:https://www.cnblogs.com/zhaosq/p/11675639.html
Copyright © 2020-2023  润新知