OpenFeign 中 hm-api、消费者、提供者依赖怎么写
·
OpenFeign 中 hm-api、消费者、提供者依赖怎么写
今天学习 Spring Cloud OpenFeign 的时候,有一个问题比较容易混:
spring-cloud-starter-loadbalancer 到底是写在 hm-api 公共模块里,还是写在服务消费者里?
项目结构
项目大概有这几个模块:
hm-api:公共 API 模块,放 FeignClient 接口和 DTOitem-service:服务提供者cart-service:服务消费者order-service:服务消费者
结论
LoadBalancer 真正生效的位置是服务消费者运行时。
也就是说:
谁发起远程调用,谁运行时就必须有 OpenFeign 和 LoadBalancer。
但是依赖不一定非要直接写在消费者的 pom.xml 里。
如果 hm-api 中已经引入了 OpenFeign 和 LoadBalancer,而消费者又依赖了 hm-api,那么消费者可以通过 Maven 依赖传递拿到这些依赖。
hm-api 中可以写
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
FeignClient 示例:
@FeignClient("item-service")
public interface ItemClient {
@GetMapping("/items/{id}")
ItemDTO queryItemById(@PathVariable("id") Long id);
}
消费者中要写
消费者比如 cart-service,只需要引入 hm-api:
<dependency>
<groupId>com.hmall</groupId>
<artifactId>hm-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
启动类上开启 Feign:
@EnableFeignClients(basePackages = "com.hmall.api.client")
@SpringBootApplication
public class CartApplication {
}
还要配置注册中心,比如 Nacos:
spring:
application:
name: cart-service
cloud:
nacos:
server-addr: localhost:8848
提供者中要写
提供者比如 item-service,主要负责注册服务并暴露接口:
spring:
application:
name: item-service
cloud:
nacos:
server-addr: localhost:8848
Controller 示例:
@RestController
@RequestMapping("/items")
public class ItemController {
@GetMapping("/{id}")
public ItemDTO queryItemById(@PathVariable Long id) {
return null;
}
}
最后总结
hm-api 里可以放 OpenFeign 和 LoadBalancer 依赖。
消费者引入 hm-api 后,可以通过依赖传递拿到这些依赖。
服务提供者如果只是被调用,不调用别人,一般不需要 OpenFeign 和 LoadBalancer。
一句话:
谁调用别人,谁运行时就必须有 OpenFeign 和 LoadBalancer。
更多推荐




所有评论(0)