服务之间相互调用
比如,订单服务需要调用库存服务。比如下订单前需要先明确是否有货,避免超订。相当于订单服务作为调用方,库存模块作为被调用方,订单服务调库存服务里面的一个接口,返回结果到订单服务。
一、库存为被调方
1、pom.xml文件。增加openfeign依赖
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、被调用函数
@RestController
@RequestMapping("/stock")
public class StockController {
/*相当于订单服务作为调用方,库存模块作为被调用方,订单服务调库存服务里面的一个接口,返回结果到订单服务*/
@RequestMapping("/test")
public String test(String info){
return "库存模块接收到的信息:"+info;
}
}
二、主动调方-订单
1、一样,pom增加依赖
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、创建service
主要@FeignClient("nacos-stock"),定义被调用的服务名
@RequestMapping("/stock/test"),是服务的路径拼接
参数用@RequestParam比如
public String test(@RequestParam("info") String info);
@RestController
@RequestMapping("/stock")
public class StockController {
/*相当于订单服务作为调用方,库存模块作为被调用方,订单服务调库存服务里面的一个接口,返回结果到订单服务*/
@RequestMapping("/test")
public String test(String info){
return "库存模块接收到的信息:"+info;
}
}
3、启动类增加包扫描注解,
@EnableFeignClients(basePackages = "com.java1234.feign")
public class NacosOrderApplication {
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.java1234.feign")
public class NacosOrderApplication {
public static void main(String[] args) {
SpringApplication.run(NacosOrderApplication.class,args);
}
}
4、测试controller
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private StockFeignService stockFeignService;
@RequestMapping("/test")
public String test(){
return stockFeignService.test("牛逼");
}
}
三、启动被调用服务-再启动主动调用服务

order日志
2026-02-24 09:59:36.270 INFO 6028 --- [nio-8082-exec-1] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client nacos-stock initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=nacos-stock,current list of Servers=[本地IP地址:8089],Load balancer stats=Zone stats: {unknown=[Zone:unknown; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:本地IP地址:8089; Zone:UNKNOWN; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
]}ServerList:com.alibaba.cloud.nacos.ribbon.NacosServerList@2a7c8035