企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## 一、Gateway网关搭建 在dongbb-cloud聚合项目的下面新建Spring Boot子项目:zimug-server-gateway 使用Spring reactive Web,即:spring-boot-starter-webflux ![](https://img.kancloud.cn/30/a3/30a387c5520dbb0089e0abc139dbade4_1554x199.png) 通过maven坐标引入gateway类库 ~~~ <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ~~~ 因为spring-cloud-starter-gateway包含spring-boot-starter-webflux,所以可以将初始化引入的spring-boot-starter-webflux的maven坐标从pom文件中删除。 ![](https://img.kancloud.cn/15/3b/153b34cbb05a803bd3f79cd8e9632c6a_653x197.png) 如果是新建的子模块module,做好父子项目的pom文件中的module配置关系。 ![](https://img.kancloud.cn/66/3e/663e2ea2627e541a8f21210518e14ae8_757x391.png) 项目的配置文件使用方法仍然和之前一致 ~~~ server: port: 8777 spring: application: name: zimug-server-gateway cloud: gateway: routes: - id: zimug-blog # 路由 ID,唯一 uri: http://zimug.com/ # 目标 URI,路由到微服务的地址 predicates: # 请求转发判断条件 - Path=/category/** # 匹配对应 URL 的请求,将匹配到的请求追加在目标 URI 之后 ~~~ * routes指的是配置路由转发规则,可以配置多个 * 每一个route有一个id,标识该路由的唯一性 * uri指的是请求转发的目标 * predicates是请求转发的判断条件,我们的例子使用的Path条件判断 上面的路由配置的含义是当我们访问:`http://<gateway-ip>:8777/category/**`的时候,请求被转发到`http://www.zimug.com/category/**`,其中`**`匹配任意字符。 ## 二、需要注意的点 我们搭建的Spring Cloud Gateway(zimug-server-gateway)项目虽然是一个web项目,但是底层已经使用的是spring-boot-starter-webflux,而不是spring-boot-starter-web。所以下面的这个坐标不要在引入gateway项目了,会报错! ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ~~~ 并且之前在spring-boot-starter-web体系下做的代码集成工作,在spring-boot-starter-webflux基础上都会有所变化,涉及到我们再去讲。 ## 三、路由转发测试 在上面的配置文件中,我们已经完成了一个简单的路由转发配置。含义是当我们访问:`http://<gateway-ip>:8777/category/**`的时候,请求被转发到`http://www.zimug.com/category/**`,其中`**`匹配任意字符。 下面我们就来做一下实验,我们把gateway项目在本机启动,然后浏览器访问如下网址。 ~~~ http://localhost:8777/category/course ~~~ 然后请求被转发至如下的网址: ~~~ http://www.zimug.com/category/course ~~~ 展现结果如下: ![](https://img.kancloud.cn/2d/87/2d87e425e5ba45f3e88b92e8aaa3586a_806x404.png)