使用SpringCloud技术栈搭建微服务集群,可以选择的组件比较多,由于有些组件已经闭源或停更,这里主要选用spring-cloud-alibaba作为我们的技术栈。
- 服务注册与发现: nacos-discovery
- 统一配置管理:nacos-config
- 微服务网关:spring cloud gateway
由于nacos本身就已经是完备的服务,故参考官方文档直接安装使用就可以,这里重点介绍如何使用SpringCloud Gateway实现路由转发和身份认证。
一、微服务架构
- 所有的请求先通过nginx进行负载和转发
- API Gateway负责进行微服务内的路由转发和身份认证
二、实现路由转发
1. 引入gateway包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
复制代码
需要注意的是:如果启动时报错,提示在依赖中发现的springMvc与gateway不能兼容,需要删除spring-boot-starter-web相关引用
**********************************************************
Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.
**********************************************************
复制代码
2. 添加启动类
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
复制代码
- @EnableDis