【Spring百口桶系列之焦点篇 | Spring Cloud】 - 第七章 把握Gateway焦点技能,实现高效路由与转发 [复制链接]
发表于 2026-4-24 09:04:17 | 显示全部楼层 |阅读模式
媒介

Spring Cloud Gateway 是一个基于 Spring Boot 的非壅闭 API 网关服务,它提供了动态路由、哀求断言、过滤器等功能
以下是关于 Spring Cloud Gateway 的示例:
示例

创建一个服务提供者


  • 新建Module
    dependency选择Spring Web及Eureka Discovery Client。
    2. 打开pom.xml文件,修改如下:
    3. 界说服务
    在src/main/java下面的com.cherry.provider 下创建新的包controller(也可以不创建新的包,在当前provider包下),并新建下面的类:
  1. package com.cherry.provider1.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. @RequestMapping("product")
  6. public class ProductController {
  7.     @RequestMapping("list")
  8.     public String list(){
  9.         
  10.         return "这是product列表";
  11.     }
  12. }
复制代码

  • 在resource中的设置文件中到场设置
  1. server.port=8009
  2. spring.application.name=my_provider1
  3. #注册中心的地址
  4. eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
复制代码

  • 修改启动类,如下:
  1. package com.cherry.provider1;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. @SpringBootApplication
  6. @EnableEurekaClient
  7. public class Provider1Application {
  8.     public static void main(String[] args) {      
  9.         SpringApplication.run(Provider1Application.class, args);
  10.     }
  11. }
复制代码

  • 打开注册中央

创建网关


  • 新建Module
    2. 修改pom.xml文件
    3. 修改设置文件application.properties,对网关举行设置
  1. server.port=9001
  2. spring.application.name=gateway
  3. spring.cloud.gateway.routes[0].id= gateway-service
  4. spring.cloud.gateway.routes[0].uri= http://localhost:8002
  5. spring.cloud.gateway.routes[0].predicates[0]= Path=/building/welcome
复制代码

  • 启动服务

创建common子项目


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表