spring cloud gateway 概述
Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。
spring cloud gateway 案例
新建一个spring boot项目,添加spring cloud相关依赖的jar包
ch18-1
cn.springcloud.book
1.0-SNAPSHOT
4.0.0
ch18-1-gateway
jar
ch18-1-gateway
http://springcloud.cn
Finchley.M8
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-starter-actuator
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.boot
spring-boot-maven-plugin
spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot
true
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
spring-snapshots
Spring Snapshots
https://repo.spring.io/snapshot
true
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
false
spring cloud gateway 网关路由方式
新的gateway网关路由配置有两种方式:
1.通过@Bean自定义RouteLocator,在启动主类Application中配置
2.在配置文件yml中配置
这两种方式都可以实现网关路由是等价的,但是通常项目开发中会使用配置文件yml方式。
启动类Application配置网关路由:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringCloudGatewayApplication {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/baidu")
.uri("http://baidu.com:80/")
).build();
}
public static void main(String[] args) {
SpringApplication.run(SpringCloudGatewayApplication.class, args);
}
}
配置文件application.yml配置网关路由:
server:
port: 8080
spring:
application:
name: spring-cloud-gateway
spring:
cloud:
gateway:
routes:
- id: 163_route
uri: http://www.163.com/
predicates:
- Path=/163
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
运行测试
配置好了,启动服务
访问 http://localhost:8080/baidu,路由转发到 http://www.baidu.com
访问http://localhost:8080/163, 路由转发到 http://www.163.com