Spring Cloud Alibaba之网关组件Gateway

实例演示1:在微服务体系中引入GateWay组件

  • 创建一个ServiceForGateway的SpringBoot项目,通过在控制类编写方法对外提供服务
java 复制代码
@RestController
public class Controller {
    @RequestMapping("/getAccount/{id}")
    public String getAccount(@PathVariable String id){
        return "Account Info, id is:"+id;
     }
}
  • 创建GatewayDemo项目,添加依赖到pom文件
XML 复制代码
 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
 </dependencies>

ps:本次实验演练仅用到Gateway组件,所以在pom文件里面,就不需要通过dependencyManagement引入spring-cloud-alibaba-dependencies,在引入了gateway的依赖后也不需要再引入spring-boot-starter-web了。

  • 配置application.yml文件相关参数,实现简单路由转发
XML 复制代码
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        # 路由id,可随便命名,但要确保唯一
        - id: account_route
          # 匹配后的地址
          uri: http://localhost:8090/getAccount/{id}
          #断言
          predicates:
            # 包含/getAccount即需转发
            - Path=/getAccount/{id}
  • 修改application.yml文件,实现网关过滤
XML 复制代码
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        - id: StripPrefix_route
          # 匹配后的地址
          uri: http://localhost:8090
          predicates:
            - Path=/needRemoved/**
          filters:
            - StripPrefix=1
        - id: PrefixPath_route
          # 匹配后的地址
          uri: http://localhost:8090
          predicates:
            - Method=GET
          filters:
            - PrefixPath=/getAccount
  • 自定义全局过滤器,设置过滤器动作:
java 复制代码
//自定义的全局性过滤器
public class MyGlobalFilter implements GlobalFilter, Ordered {
    //处理请求
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String urlPath = exchange.getRequest().getURI().getPath();
        System.out.println(urlPath);
        if(urlPath.indexOf("hacker") == -1){
            return chain.filter(exchange);
        }
        else{
            ServerHttpResponse res = exchange.getResponse();
            String msg = "fail for hacker";
            byte[] bits = msg.getBytes();
            DataBuffer buf = res.bufferFactory().wrap(bits);
            res.setStatusCode(HttpStatus.BAD_REQUEST);
            res.getHeaders().add("Content-Type", "text/plain");
            return res.writeWith(Mono.just(buf));
        }
    }
    @Override
    public int getOrder() {
        //Order值越小,优先级越高
        return 0;
    }
}
  • 编写代码配置过滤器:
java 复制代码
@Configuration
public class ConfigMyGlobalFilter {
    @Bean
    public GlobalFilter configFilter() {
        return new MyGlobalFilter();
    }
}

实例演示2:GateWay整合Nacos,实现负载均衡

  • 创建 GateWithNacos项目,添加pom依赖,引入nacos和GateWay依赖包
XML 复制代码
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
</dependencies>
  • 编写启动类,添加注解,说明项目与nacos组件交互
java 复制代码
@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }

}
  • 配置application.yml文件,实现GateWay整合Nacos效果
java 复制代码
server:
  port: 8080
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: loadbalance_route
          uri: lb://ServiceProvider/
          predicates:
            - Path=/callServiceByRibbon

实例演示3:通过GateWay实现灰度发布

  • 创建GrayRelease项目,添加pom依赖,启动类同上一致
XML 复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>
  • 配置application.yml文件,实现灰度发布效果
XML 复制代码
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        - id: oldVersion_Route
          uri: http://localhost:3333/getAccount/{id}
          predicates:
            - Path=/getAccount/{id}
            - Weight=accountGroup, 9
        - id: newVersion_Route
          uri: http://localhost:5555/getAccount/{id}
          predicates:
            - Path=/getAccount/{id}
            - Weight=accountGroup, 1
相关推荐
JJJennie7772 小时前
MAI Gateway私有化部署全攻略:大模型网关接入DeepSeek?附架构图
大模型·gateway·ai网关·魔芋ai
蜗牛8753 小时前
为 Spring Boot 团队做一个 Elasticsearch 查询工作台:六种模式、语义补全与浏览器直连
spring boot
养军博客6 小时前
Spring Boot 3.x + Spring Security 6.x 整合 JWT 实战:jjwt 与 java-jwt 两种工具库详解
java·spring boot·springsecurity
txxzjmzlh17 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
秋天的怀念_David1 天前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
余槐i1 天前
MySQL 8.0 联合索引走错:为什么加了索引查询反而从 200ms 变成 8s
java·spring boot·mysql·docker·性能优化
程序员沉梦听雨1 天前
【搜索引擎】Kibana使用指南
java·后端·学习笔记
nice_lcj5201 天前
【从零理解 Spring AI · 03】Spring AI 在 Spring 生态里的位置
java·spring boot·大模型·spring ai·ai应用开发
AI源码2 天前
旅游推荐管理系统
spring boot
aiks_yuan2 天前
Spring Boot SSE 流式输出变成一次性返回怎么办:大模型打字机效果失效的 5 个原因(Spring Boot 4.1.2 实测)
spring boot