Spring Cloud Gateway可通过配置文件或Java代码配置路由,推荐使用yml方式。示例中通过Path断言匹配请求路径,StripPrefix过滤器去除前缀后转发至指定uri;也可通过RouteLocatorBuilder编写Java配置实现更灵活的路由逻辑;结合Eureka时使用lb://协议实现服务发现与负载均衡;需注意避免引入spring-webmvc以防止与WebFlux冲突,且路由顺序影响匹配优先级。

在Java后端开发中,Spring Cloud Gateway 是微服务架构里常用的网关组件,负责请求的路由转发和过滤。配置路由是它的核心功能之一。你可以通过两种方式来配置:一种是使用配置文件(推荐),另一种是通过 Java 代码硬编码。
这是最常见、最简洁的方式。你只需要在 application.yml 文件中定义路由规则即可。
示例配置:
spring:
cloud:
gateway:
routes:
- id: user-service-route
uri: http://localhost:8081
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
<pre class='brush:java;toolbar:false;'> - id: order-service-route
uri: http://localhost:8082
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1说明:
立即学习“Java免费学习笔记(深入)”;
lb://userservice)。Path=/api/users/** 表示路径以 /api/users/ 开头的请求会被转发。StripPrefix=1 表示去掉第一层路径前缀再转发。比如 /api/users/list 转发到后端时变为 /list。如果你需要更灵活的控制,可以用 Java 代码定义路由。
示例:
@Configuration
public class GatewayConfig {
<pre class='brush:java;toolbar:false;'>@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user_route", r -> r.path("/api/users/**")
.filters(f -> f.stripPrefix(1))
.uri("http://localhost:8081"))
.route("order_route", r -> r.path("/api/orders/**")
.filters(f -> f.stripPrefix(1))
.uri("http://localhost:8082"))
.build();
}}
这种方式适合动态或条件性路由逻辑,但日常使用中 yml 更清晰。
在微服务场景下,通常配合注册中心(如 Eureka)使用,让网关自动发现服务实例。
配置示例:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
注意:uri 使用 lb:// 前缀表示启用负载均衡,user-service 是服务在 Eureka 中注册的名称。
确保以下几点避免常见错误:
spring-cloud-starter-gateway 和 spring-cloud-starter-netflix-eureka-client(如果用了注册中心)。spring-webmvc,否则会与 WebFlux 冲突。基本上就这些。用 yml 配置路由简单高效,适合大多数场景。结合服务发现后,网关能自动路由到正确的微服务。
以上就是java后端开发中Spring Cloud Gateway怎么配置路由?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号