gateway的在springboot中的使用
时间: 2024-04-04 16:29:07 浏览: 52
在 Spring Boot 中使用 Gateway 需要进行如下步骤:
1. 添加依赖
在 `pom.xml` 文件中添加如下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
```
2. 配置路由
在 `application.yml` 文件(或 `application.properties` 文件)中添加路由配置,例如:
```yml
spring:
cloud:
gateway:
routes:
- id: service1_route
uri: http://localhost:8081
predicates:
- Path=/service1/**
- id: service2_route
uri: http://localhost:8082
predicates:
- Path=/service2/**
```
上述配置将请求路径为 `/service1/**` 的请求转发到 `http://localhost:8081`,请求路径为 `/service2/**` 的请求转发到 `http://localhost:8082`。
3. 启用 Gateway
在启动类中添加 `@EnableDiscoveryClient` 和 `@EnableGateway` 注解,例如:
```java
@SpringBootApplication
@EnableDiscoveryClient
@EnableGateway
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
```
4. 运行服务
启动服务后,即可通过 Gateway 访问转发的服务。例如,访问 `http://localhost:8080/service1/hello` 将会转发到 `http://localhost:8081/hello`。
阅读全文
相关推荐


















