首页 文章资讯内容详情

SpringCloud 服务间互相调用 @FeignClient注解

2026-06-01 4 花语

本文内容纲要:

SpringCloud搭建各种微服务之后,服务间通常存在相互调用的需求,SpringCloud提供了@FeignClient注解非常优雅的解决了这个问题

首先,保证几个服务都在一个Eureka中注册成功形成服务场。

如下,我一共有三个服务注册在服务场中。COMPUTE-SERVICE;FEIGN-CONSUMER;TEST-DEMO;

现在,我在FEIGN-CONSUMER服务中调用其他两个服务的两个接口,分别为get带参和post不带参两个接口如下

这个是COMPUTE-SERVICE中的get带参方法

1@RequestMapping(value="/add",method=RequestMethod.GET) 2publicIntegeradd(@RequestParamIntegera,@RequestParamIntegerb){ 3ServiceInstanceinstance=client.getLocalServiceInstance(); 4Integerr=a+b; 5logger.info("/add,host:"+instance.getHost()+",service_id:"+instance.getServiceId()+",result:"+r); 6returnr; 7}

如果要在FEIGN-CONSUMER服务中调用这个方法的话,需要在FEIGN-CONSUMER中新建一个接口类专门调用某一工程中的系列接口

1@FeignClient("compute-service") 2publicinterfaceComputeClient{ 3 4@RequestMapping(method=RequestMethod.GET,value="/add") 5Integeradd(@RequestParam(value="a")Integera,@RequestParam(value="b")Integerb); 6 7}

其中,@FeignClient注解中标识出准备调用的是当前服务场中的哪个服务,这个服务名在目标服务中的配置中取

1spring.application.name

接下来,在@RequestMapping中设置目标接口的接口类型、接口地址等属性。然后在下面定义接口参数以及返回参数

最后,在FEIGN-CONSUMERController层调用方法的时候,将上面接口注入进来,就可以直接用了 1@Autowired 2ComputeClientcomputeClient; 3 4@RequestMapping(value="/add",method=RequestMethod.GET) 5publicIntegeradd(){ 6returncomputeClient.add(10,20); 7}

当然,post方法同理:

这是目标接口:

1@RestController 2@RequestMapping("/demo") 3@EnableAutoConfiguration 4publicclassHelloController{ 5@RequestMapping(value="/test",method=RequestMethod.POST) 6Stringtest1(){ 7return"hello,test1()"; 8} 9}

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

1@FeignClient("test-Demo") 2publicinterfaceTestDemo{ 3@RequestMapping(method=RequestMethod.POST,value="/demo/test") 4Stringtest(); 5} 这是项目中的Controller层: 1@RestController 2publicclassConsumerController{ 3@Autowired 4TestDemotestDemo; 5 6@Autowired 7ComputeClientcomputeClient; 8 9@RequestMapping(value="/add",method=RequestMethod.GET) 10publicIntegeradd(){ 11returncomputeClient.add(10,20); 12} 13 14@RequestMapping(value="/test",method=RequestMethod.GET) 15publicStringtest(){ 16returntestDemo.test(); 17} 18}

最终调用结果如下:

OK服务间接口调用就是这样了!

本文内容总结:

原文链接:https://www.cnblogs.com/zhaosq/p/11675639.html