本文共 3774 字,大约阅读时间需要 12 分钟。
Spring Cloud Gateway 是一款功能强大且灵活的网关解决方案,主要用于对内外部服务进行路由转发和请求过滤。在实际应用中,客户端向网关发送请求时,网关会根据预定义的路由规则判断请求是否需要转发给目标服务。具体来说:
在开始使用 Spring Cloud Gateway 之前,需要先完成以下操作:
创建 Maven 项目并添加依赖
pom.xml 文件应包含以下内容:org.springframework.cloud spring-cloud-gateway 2.0.0.RELEASE import org.springframework.cloud spring-cloud-starter-gateway 2.0.0.RELEASE
创建启动类
Application.java 中定义启动类,确保类注解 @SpringBootApplication 存在。import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}运行应用
mvn spring-boot:run 启动应用,默认情况下会在 http://localhost:8080 上运行。http://localhost:8080/ 会提示 404 错误,日志中会显示类似的错误信息。通过配置文件实现路由配置是一个直观且常用的方法。假设你有本地运行的两个 Spring Boot 服务(如服务A在 http://localhost:8081 和服务B在 http://localhost:8082),可以按照以下步骤配置路由:
添加配置文件
resources 目录下创建 application.yml 文件,添加如下路由配置:spring: cloud: gateway: routes: - id: host_route uri: http://localhost:8081 predicates: - Path=/a/** filters: - StripPrefix=1 - id: host_route uri: http://localhost:8082 predicates: - Path=/b/** filters: - StripPrefix=1
重启 Gateway 服务
测试路由配置
http://localhost:8080/a/ 应能成功路由到 http://localhost:8081/。http://localhost:8080/b/ 同样应能成功路由到 http://localhost:8082/。http://localhost:8080/a/user/all 也会正确路由到目标服务。除了配置文件方式,还可以通过编码实现路由配置,这种方法适合需要自定义路由逻辑的场景:
删除配置文件
application.yml 中删除相关路由配置。修改启动类
Application.java 中添加自定义路由配置,确保类路径正确:import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class Application { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { StripPrefixGatewayFilterFactory.Config config = new StripPrefixGatewayFilterFactory.Config(); config.setParts(1); return builder.routes() .route("host_route", r -> r.path("/a/**").filters(f -> f.stripPrefix(1)).uri("http://localhost:8081")) .route("host_route", r -> r.path("/b/**").filters(f -> f.stripPrefix(1)).uri("http://localhost:8082")) .build(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Spring Cloud Gateway 提供了丰富的路由规则和过滤器选项,例如:
AddRequestHeader、AddRequestParameter、AddResponseHeader 等,帮助开发者实现更复杂的网关逻辑。通过合理配置,可以在短时间内搭建一个功能强大的网关服务,满足各种微服务架构的需求。
转载地址:http://cpjuz.baihongyu.com/