Feign 远程调用:调用的是对方项目的 Controller,不是 Service
目录
一、核心结论
二、举完整例子
1)提供者服务(user-service)Controller(对外入口)
2)消费者 Feign 接口(对齐 Controller)
3)消费者业务 Service 调用 Feign
三、关键区分
四、常见误区
补充:如果是 Dubbo 就不一样
一、核心结论
- 服务提供方(被调用方)对外暴露接口写在
Controller,接收 HTTP 请求; Service 只是内部业务实现,不对外暴露网络接口。 - 服务消费方(调用方,Feign 这边)Feign 定义的接口,签名必须和对方 Controller 完全对应,模拟 HTTP 请求去访问对方 Controller。
- Service 只存在于各自服务内部,跨服务不能直接调用 Service。
二、举完整例子
1)提供者服务(user-service)Controller(对外入口)
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/get/{id}") public User getById(@PathVariable Long id) { // 内部调用自己的Service return userService.getById(id); } }2)消费者 Feign 接口(对齐 Controller)
// Feign接口 = 远程Controller的镜像 @FeignClient(name = "user-service") public interface UserFeignClient { // 路径、请求方式、参数、注解 完全和对方Controller一致 @GetMapping("/user/get/{id}") User getUser(@PathVariable Long id); }3)消费者业务 Service 调用 Feign
@Service public class OrderService { @Autowired private UserFeignClient userFeignClient; public void createOrder(Long userId) { // 通过Feign发起HTTP,远程访问 user-service 的 UserController User user = userFeignClient.getUser(userId); } }三、关键区分
- Controller:网络出入口处理 HTTP,跨服务通信唯一入口,Feign 实际访问的目标。
- Service:本地业务层仅本项目内部使用,没有 HTTP 能力,无法远程访问。
- Feign 本质是 HTTP 客户端,走网络请求,只能访问 HTTP 接口(Controller)。
四、常见误区
- ❌ 错误:Feign 对应对方 Service Service 没有请求路径、没有 @GetMapping,无法接收网络调用;
- ✅ 正确:Feign 是远程 Controller 的镜像接口,用来拼装 HTTP 请求。
补充:如果是 Dubbo 就不一样
Dubbo 走 RPC,直接暴露 Service 接口远程调用; Feign 基于 OpenFeign + HTTP,是 REST 风格,只能对接 Controller。
