1.为什么需要
在微服务项目中,一个项目会被拆分成很多个服务,各个服务有各自的访问地址(端口和IP)。对前端开发人员而言,调用不同的服务需要不断修改访问地址,这无疑增加了调用接口的复杂度,也容易造成调用失败。那么我们可不可以使用某一种工具,将所有接口统一起来,简化调用过程。Gateway 就是这样一种工具。Gateway(网关)可以理解为网络的开关,所有请求到达Gateway 后将请求转发到具体服务。
2 使用步骤
2.1 准备工作
首先需要启动 Nacos服务,将所有服务注册到服务中心。Gateway 通过查询服务中心的服务来进行请求的转发。
2.2 启动Gateway 服务
1.创建新模块,依赖导入
注意Gateway 服务内部基于Netty 实现,会和spring web冲突。所以我们的依赖中不能出现web 相关依赖,新的模块直接继承最基础的环境就行。
父模块环境
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 搭建微服务基础架构-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR3</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
Gateway 服务依赖
<dependencies>
<!-- GateWay -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<!-- Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
</dependencies>
2. 创建启动类,配置文件
1. 启动类
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
2. 配置文件
server:
port: 8686
spring:
application:
name: gateway
cloud:
gateway:
globalcors:
#统一配置跨域问题,不需要去每个服务里面配置跨域
cors-configurations:
'[/**]':
#访问前端的地址
allowed-origins:
- "http://localhost:8383"
- "http://localhost:8282"
allowed-headers: "*"
allowed-methods: "*"
max-age: 3600
discovery:
locator:
enabled: true
3. 启动服务
依次启动nacos 相关服务、Gateway 服务 ,启动以后就可以使用gateway的端口+服务名+服务的具体地址进行访问了
http://localhost:8686/order-service/seller/order/list/1/10
后面在前端的调用中,只需要都可以通过相同的请求路径(IP+端口)去请求后端服务,通过服务名进行区分