1. 依赖
代码语言:javascript
复制<!-- 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 服务网关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2. 配置
代码语言:javascript
复制spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: '*'
allowedHeaders: '*'
allowedMethods: '*'
allowCredentials: true
discovery:
locator:
enabled: true
lowerCaseServiceId: true
3. 启动类
代码语言:javascript
复制@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4. 注意
- 如果服务已经启用CORS过滤器,则无需再gateway上配置CORS否则会导致错误
- 使用nacos做服务注册中心时,服务必须与gateway注册在同一个名空间以及分组下,才会被自动发现定位。