简单来说,这是zuul的替代品,现在开撸!
1.1开始新建一个项目,增加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
1.2 增加配置文件配置
eureka:
client:
service-url:
defaultZone: http://user:user@demo-springcloud-eureka-one:8761/eureka/
instance:
prefer-ip-address: true
spring:
application:
name: demo-springcloud-gateway
server:
port: 8800
1.3 增加启动类上的代码
@EnableDiscoveryClient
@SpringBootApplication
public class DemoSpringcloudGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringcloudGatewayApplication.class, args);
}
}
1.4 配置路由的规则,两种方式,一种代码形式,一种配置形式
1.5 一些逻辑配置样例
spring:
cloud:
gateway:
#可以根据请求参数,cookie,host,请求时间,请求头等进行校验判断路由, 下面根据先后顺序转发
routes:
- id: host_route
uri: http://localhost:8866/
predicates:
- Path=/order/** # 请求地址携带order的,则转发
- id: host_route
uri: http://localhost:8866/get
predicates:
- Host=**.csdn.** # 请求域名携带csdn的,则转发
- id: query_route
uri: http://localhost:8866/get
predicates:
- Query=username, zzz* # 请求参数含有username,且值满足zzz开头的,则转发(对值的匹配可以省略)
- id: header_route
uri: http://localhost:8866/get
predicates:
- Header=request, \d+ # 如果请求头含有request,且为数字,则转发
- id: cookie_route
uri: http://localhost:8866/get
predicates:
- Cookie=name, zzzgd # 如果携带cookie,参数名为name,值为zzzgd,则转发
- id: path_route
uri: http://localhost:8866/get
predicates:
- Path=/zzzgd/** # 请求地址携带zzzgd的,则转发
# 路由到其他服务,url需要用[lb://]+[serviceId]
- id: service_client
uri: lb://service-client
predicates:
- Path=/api-a/** # 如果请求地址满足/api-a/**,则转发到 service-client 服务
filters:
- StripPrefix=1 # 去除请求地址中的to_client
- id: after_route
uri: http://localhost:8866/get
predicates:
- After=2019-03-01T17:42:47.789-07:00[America/Denver] # 如果请求时间大于该时间,则转发
1.6 代码配置形式举例
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/zuul")
.filters(f -> f.addRequestHeader("Hello", "lemon"))
.uri("http://localhost:8866/"))
.build();
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri(" http://localhost:8866"))
.route(p -> p
.host("*.lemon.com")
.filters(f -> f.hystrix(config -> config
.setName("test")
.setFallbackUri("forward:/fallback")))
.uri(" http://localhost:8866"))
.build();
}