Spring Cloud Gateway 基本使用
maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
spring 版本
Spring Boot 2.0.5.RELEASE
Spring Cloud Finchley.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
启动类注解
@SpringCloudApplication
yml配置
Spring Cloud Gateway 基于Eureak的服务发现弊端:通过网关转发服务调用,访问王福安的uri默认必须是大写,否则报404;
通过指定配置可以解决:spring.cloud.gateway.discovery.locator.owerCaseServiceId: true
以Zookeeper或Consul为注册中心,不会出现这个情况
这是基于Spring Cloud 的路由转发
spring:
cloud:
gateway:
discovery:
locator:
enabled: false
lowerCaseServiceId: true
routes:
- id: service-hi
uri: lb://SERVICE-HI
predicates:
- Path=/demo/**
filters:
- StripPrefix=1
配置说明
spring.cloud.gateway.discovery.locator.enabled: false
是否与服务发现组件进行组合,通过serviceId转发到具体的服务实例。默认为false,若为true便开启基于服务发现的路由规则
spring.cloud.gateway.discovery.locator.lowerCaseServiceId: true
当注册中心为Eureka时,设置为true标识开启用小写的serviceId进行基于服务路由转发
以下是基于url转发
spring:
cloud:
gateway:
routes:
- id: before_route
uri: https://example.org
也可以使用java代码来配置路由规则
@Bean
public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
.route(r -> r.path("/test/**")
.uri("http://localhost:8762/hi")
.id("rateLimit_route")
)
.build();
}
如果java代码合yml配置同时存在,优先于java代码中的配置