×
文章目录
摘要:本篇文章主要介绍了什么是Spring Cloud Gateway
,并基于Spring Cloud Gateway的Finchley.M8版本编写一个Spring Cloud Gateway的入门案例,即基本代理的路由转发配置。
1.Spring Gateway概述
1.1 什么是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链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。
2. Spring Cloud Gateway入门案例
2.1 创建maven工程
配置Spring Cloud Gateway的相关Maven依赖
|
|
2.2 Spring Cloud Gateway主程序
SpringCloudGatewayApplication.java,代码如下所示:
|
|
2.3 编写application.yml文件
|
|
2.4 基本代理路由配置等同写法
Spring Cloud Gateway提供了两种配置路由规则的方法
- 第一:通过@Bean自定义RouteLocator12345678public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {return builder.routes()//basic proxy.route(r -> r.path("/baidu").uri("http://baidu.com:80/")).build();}
- 第二:通过属于文件或者yml文件配置
|
|
PS,以上两种方式等同。
2.5 错误的示范代码如下:
|
|
温馨提示,上面这种写法是基于Spring Cloud Gateway FM4的版本,相关代码已废弃,目前Spring Cloud Gateway将会在FM9之后Realese。
2.6 运行测试
- 访问http://localhost:8080/baidu,路由转发到http://www.baidu.com
- 访问http://localhost:8080/xujin,路由转发到http://xujin.orgyml
|
|
|
|
如果您觉得文章不错,可以打赏我喝一杯咖啡!