【学习笔记】API网关(GateWay)

项目场景

提示:这里可以添加本文要记录的大概内容:

微服务将一个大型工程转成了诺干个微服务,每个微服务都是一个独立的项目因此每一个项目都有不同的端口,那我们怎样在前端发送请求的时候能精确的发送到我们所需要的服务里。


提示:以下是本篇文章正文内容,下面案例可供参考

一、GateWay是什么?

Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

gateway几个重要的概念:在这里插入图片描述
gateway怎么用:
Predicate 就是为了实现一组匹配规则,方便让请求过来找到对应的 Route 进行处理,接下来我们接下 Spring Cloud GateWay 内置几种 Predicate 的使用。

二、使用

<1> 导包

<dependency>
          <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

导入包之后,我们配置一下,主要的配置就是上边几个核心概念:
routes(路由)、predicates(断言)、filters(过滤器)

server:
    port: 88
spring:
    application:
        name: jdmall-gateway
    cloud:
        nacos:
            discovery:
                server-addr: 127.0.0.1:8848
        gateway:
            routes:
              - id: product_route
                uri: lb://jdmall-product #去注册中心找到jdmall-product 的地址为localhoast:10000
                predicates:
                  - Path=/api/product/**  #只要前端发起请求带/api/product前缀就默认让网关路由到jdmall-product上
                filters:
                  - RewritePath=/api/(?<segment>.*),/$\{segment} # 重写路径吧 /api 前缀去掉

              - id: third_service
                uri: lb://jdmall-thirdService
                predicates:
                  - Path=/api/thirdService/**
                filters:
                  - RewritePath=/api/(?<segment>.*),/$\{segment}

              - id: admin_route
                uri: lb://renren-fast  #lb为负载均衡 renren-fast去注册中心找,找到的地址为localhoast:8080
                predicates:
                  - Path=/api/**               #只要前端发起请求带/api前缀就默认让网关路由到renren-fast上
                filters:
                  - RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}  # 把/api去掉 改变成 /renren-fast/*

以上简单的配置一下,在使用之前肯定得注册到nacos里,gateway主要是在nacos里寻找服务,最终路由到相应的微服务里 **

     uri: lb://jdmall-product #去注册中心找到jdmall-product 的地址为localhoast:10000,lb是负载均衡

lb后边是nacos服务名称

predicates:
     - Path=/api/product/** 

断言:前端只要发送请求端口为88并携带/api/product这前缀,就会精确路由到nacos里对应的服务中。

 filters:
   - RewritePath=/api/(?<segment>.*),/$\{segment} # 重写路径吧 /api 前缀去掉

过滤器有多种过滤方式,具体看SpringCloudAlibabaGateWay官方文档

这里只看路径重写 RewritePath :
这里的意思是将前边/api/请求头去除掉,留下后边的
路径重写之前的请求是:http://localhost:88/api/product/xxxxxx
重写之后且路由成功的路径为:http://localhost:10000/product/xxxxxx
(后端product端口为10000)

本人小白,记录一下日常,大佬勿喷!!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值