SpringCloudAlibaba Gateway(一)简单集成

这篇具有很好参考价值的文章主要介绍了SpringCloudAlibaba Gateway(一)简单集成。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SpringCloudAlibaba Gateway(一)简单集成

随着服务模块的增加,一定会产生多个接口地址,那么客户端调用多个接口只能使用多个地址,维护多个地址是很不方便的,这个时候就需要统一服务地址。同时也可以进行统一认证鉴权的需求。那么服务网关就充当这样的角色。

Gateway

​ 网关为众多微服务挡在前面,做路由转发、监控、限流、鉴权等功能。SpringCloudGateway就是其实现之一。SpringCloudGateway借鉴了Spring Cloud Netfilix Zuul的思想,它的目标是替代Zuul。

Gateway是基于WebFlux框架实现的,而WebFlux底层是使用高性能框架Netty,性能方面是Zuul的1.6倍,且功能强大,设计优雅。

​ Gateway的核心是路由Predicate(断言)Filter(过滤器)。路由是转发规则,Predicate是判断,Filter可以认为是请求被路由前或后加一点自定义逻辑。

SpringCloudGateway需要使用SpringBoot2.0+及以上版本,并且不可以在Tomcat或Jetty等Servlet容器运行,必须是Jar包运行!!!

集成Gateway

构建一个Gateway网关服务,再创建两个服务:用户服务和商品服务,架构如下:

SpringCloudAlibaba Gateway(一)简单集成,SpringCloud,SpringBoot,gateway,springcloud

user服务UserController,用户服务端口8002

@RestController
public class UserController {
    private final Map<Integer, String> userInfo = new HashMap<Integer, String>() {{
        put(1, "Zhangsan");
        put(2, "Lisi");
    }};
    @RequestMapping("/user/findById")
    public String findById(@RequestParam("id") Integer id) {
        return userInfo.getOrDefault(id, null);
    }
}

shop服务ShopController,商品服务端口8003

@RestController
public class ShopController {
    private final Map<Integer, String> shopInfo = new HashMap<Integer, String>() {{
        put(1, "这是苹果");
        put(1024, "芒果");
    }};
    @RequestMapping("/shop/findById")
    public String findById(@RequestParam("id") Integer id) {
        return shopInfo.getOrDefault(id, null);
    }
}

创建一个gateway的服务

依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Gateway中去除spring-boot-starter-web依赖,gateway中有webflux依赖,与starter-web有冲突。

bootstrap.yml加入配置

server:
  port: 8083

spring:
  application:
    name: gateway   # 服务名
  
  cloud:
    gateway:
	  routes: # 路由,可配置多个
        - id: user_route  # 路由id,唯一即可,默认UUID
          uri: http://localhost:8002  # 路由地址(匹配成功后的服务地址)
          order: 1  # 路由优先级,默认0,越低优先级越高
          predicates:
            - Path=/user/**   # 断言,匹配规则

        - id: shop_route
          uri: http://localhost:8003
          order: 1
          predicates:
          - Path=/shop/**

网关配置也可以使用JavaConfig的方式,但是不推荐使用。

配置中表示,当请求网关路径中地址是以/user/开头就路由到用户服务中,/shop/开头路由到商品服务中。

测试一下

C:\Users\Admin>curl http://localhost:8083/user/findById?id=1
Zhangsan
C:\Users\Admin>curl http://localhost:8083/shop/findById?id=1024
芒果

Gateway整合nacos

上面案例中,uri都是写死的一些东西,如果对应的具体服务地址改了,那么就需要修改配置文件,而且假如要提高用户承载量,做负载均衡,有很多个节点,肯定不能只配置一个服务地址。

那么就需要用到nacos,统一管理服务注册、发现,网关路由转发的地址从nacos中拿就行。

那么用户服务商品服务需要引入nacos服务发现注册依赖

<!-- 服务注册  服务发现需要引入的 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!--健康监控-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

bootstrap.yml文件

------------------------User服务
server:
  port: 8002
spring:
  application:
    name: user # 应用名

  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址
        
--------------------------Shop服务
server:
  port: 8003
spring:
  application:
    name: shop # 应用名

  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos服务地址

最后记得启动类上,启动nacos服务注册发现

@SpringBootApplication
@EnableDiscoveryClient	// 启用服务注册发现
public class UserApp {

    public static void main(String[] args) {
        SpringApplication.run(UserApp.class, args);
    }
}

欧克,那么同样地,gateway服务也要启用服务注册发现

依赖

<!-- 服务注册  服务发现需要引入的 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

bootstrap.yml配置如下:

server:
  port: 8083

spring:
  application:
    name: gateway   # 服务名

  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos地址
    gateway:
      discovery:
        locator:
          enabled: true # 让gateway可以发现nacos中的服务,gateway自动根据服务发现为每一个服务创建了一个router,# 这个router将以服务名开头的请求路径转发到对应的服务
      routes: # 路由,可配置多个
      - id: user_route  # 路由id,唯一即可,默认UUID
        uri: lb://user  # 路由地址(匹配成功后的服务地址) user是用户服务的服务名称
        order: 1  # 路由优先级,默认0,越低优先级越高
        predicates:
        - Path=/user/**   # 断言,匹配规则

      - id: shop_route
        uri: lb://shop  # 路由地址(匹配成功后的服务地址) shop是商品服务的服务名称
        order: 1
        predicates:
        - Path=/shop/**

启动尝试下:

C:\Users\Admin>curl http://localhost:8083/user/findById?id=1
{"timestamp":"2023-08-05T00:34:40.684+00:00","path":"/user/findById","status":503,"error":"Service Unavailable","requestId":"f5f6d217-1"}
C:\Users\Admin>curl http://localhost:8083/user/findById?id=1
{"timestamp":"2023-08-05T00:35:50.223+00:00","path":"/user/findById","status":503,"error":"Service Unavailable","requestId":"21a722a2-1"}

哈?服务不可用,经查阅资料得知:缺少ReactiveLoadBalancerClientFilter过滤器,需要LoadBalancerClientFactory类,但是需要引入相关依赖

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

可以了,再试下:

C:\Users\Admin>curl http://localhost:8083/shop/findById?id=1024
{"timestamp":"2023-08-05T01:19:34.183+00:00","status":404,"error":"Not Found","path":"/findById"}
C:\Users\Admin>curl http://localhost:8083/user/findById?id=1
{"timestamp":"2023-08-05T01:19:34.183+00:00","status":404,"error":"Not Found","path":"/findById"}

好嘞漂亮,踩了大坑了!!!一直404!!!

经过百般挣扎,查资料,看源码,调试等等手段,明白原因了…

spring:
  application:
    name: gateway   # 服务名
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos地址
    gateway:
      discovery:
        locator:
          enabled: true # 让gateway可以发现nacos中的服务,gateway自动根据服务发现为每一个服务创建了一个router,# 这个router将以服务名开头的请求路径转发到对应的服务

重点来了注意看:

当你的gateway配置了locator.enabled: true时,gateway自动根据服务发现为每一个服务创建了一个router, 这个router将以服务名开头的请求路径转发到对应的服务,相当于人家给你自动生成了route规则,你自己都不用配置了

但是:你的请求中必须要带着服务端的服务名才可以进行访问到

以上述为例:如果要访问到user服务的/user/findById,那么请求地址为localhost:8083/user/user/findById

C:\Users\Admin>curl http://localhost:8083/user/user/findById?id=1
Zhangsan

如何选择

提供两种写法:

  • 实际上,如果项目路径比较简单,直接让gateway和nacos自动生成即可

    spring:
      application:
        name: gateway   # 服务名
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848 # nacos地址
        gateway:
          discovery:
            locator:
              enabled: true # 让gateway可以发现nacos中的服务,gateway自动根据服务发现为每一个服务创建了一个router,# 这个router将以服务名开头的请求路径转发到对应的服务
    

    请求时,记得带上服务端的application.name名称即可,如locahost:8083/user/user/findById,第一个user是服务名称

  • 假如不想这么做,想直接以一个路径,跳到对应的服务中去,不去写服务名,那么我们需要自定义routes

    server:
      port: 8083
    
    spring:
      application:
        name: gateway   # 服务名
    
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848 # nacos地址
        gateway:
          routes: # 路由,可配置多个
          - id: user_route  # 路由id,唯一即可,默认UUID
            uri: lb://user  # 路由地址(匹配成功后的服务地址) user是用户服务的服务名称
            order: 1  # 路由优先级,默认0,越低优先级越高
            predicates:
            - Path=/user/**   # 断言,匹配规则
    

    不使用nacos自动生成的routes,自己定义,那么我们访问时localhost:8083/user/findById就能正常访问到user服务下的/user/findById资源了。

    C:\Users\Admin>curl http://localhost:8083/user/findById?id=1
    Zhangsan
    

两种方式都可以使用,根据项目的实际情况选择。locator.enabled: true只要在gateway中配置了,那么你在进行网关路由时,请求地址的第一个目录一定是服务名称文章来源地址https://www.toymoban.com/news/detail-691383.html

到了这里,关于SpringCloudAlibaba Gateway(一)简单集成的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringCloud Alibaba集成 Gateway(自定义负载均衡器)、Nacos(配置中心、注册中心)、Loadbalancer

    路由(route):路由是网关最基础的部分,路由信息由一个ID,一个目的URL、一组断言工厂和一 组Filter组成。如果断言为真,则说明请求URL和配置的路由匹配。 断言(Predicate):Java8中的断言函数,Spring Cloud Gateway中的断言函数输入类型是 Spring5.0框架中的ServerWebExchange。Sprin

    2024年04月12日
    浏览(45)
  • SpringCloudAlibaba之Gateway

    1、简介         网关是系统唯一对外的入口,介于客户端与服务器端之间,用于对请求进行鉴权、限流、路由、监控等功能。 2、Gateway主要功能 2.1、 route 路由 路由是网关的最基本组成,由一个路由 id、一个目标地址 url,一组断言工厂及一组 filter 组成。若断言为 true,

    2024年01月19日
    浏览(25)
  • 【微服务 SpringCloudAlibaba】实用篇 · Gateway服务网关

    微服务(8) Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等响应式编程和事件流技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。 Gateway网关是我们服务的守门神,所有微服务的统一入口

    2024年02月01日
    浏览(31)
  • SpringCloudAlibaba:服务网关之Gateway的cors跨域问题

    目录 一:解决问题 二:什么是跨域 三:cors跨域是什么?  遇到错误:         前端请求时报错 解决: 网关中添加配置文件, 注意springboot版本 ,添加配置。 跨域是指浏览器处于安全考虑,对 JavaScript 发起的不同源的请求进行限制的一种机制。 所谓同源是指协议,域名和

    2024年02月15日
    浏览(31)
  • 【Spring Cloud Gateway】⑥SpringBoot3.x集成SpringDoc指南

    Spring Cloud Gateway 使用 Netty 作为嵌入式服务器,并基于响应式 Spring WebFlux 。做为微服务网关,多个微服务把 API 挂在 Gateway 上,如果查看某个 API 的 Swagger 还要去各个子微服务中去查看,就很不方便,如果能在 Gateway 上直接查看各个微服务的 API 文档,会方便很多,本文以截至

    2024年02月14日
    浏览(36)
  • SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控

    ​ 前面使用过Sentinel组件对服务提供者、服务消费者进行流控、限流等操作。除此之外,Sentinel还支持对Gateway、Zuul等主流网关进行限流。 ​ 自sentinel1.6.0版开始,Sentinel提供了Gateway的适配模块,能针对路由(route)和自定义API分组两个维度进行限流。 路由维度是指配置文件中的

    2024年02月10日
    浏览(28)
  • SpringCloudAlibaba Gateway(二)详解-内置Predicate、Filter及自定义Predicate、Filter

    ​ Predicate(断言),用于进行判断,如果返回为真,才会路由到具体服务。SpirnngCloudGateway由路由断言工厂实现,直接配置即生效,当然也支持自定义路由断言工厂。 ​ SpringCloudGateway路由断言工厂实现有很多,可以帮助开发者完成不同的功能。 AfterRoutePredicateFactory :设定日期参

    2024年02月10日
    浏览(35)
  • 【SpringCloud】SpringCloud Gateway详解

    微服务分为多个服务,有很多服务是内部人员要用的,但是现在谁都可以访问到,那我们该怎么办呢? Spring Cloud最新面试题 Spring Cloud Nacos详解之注册中心 Spring Cloud Nacos详解之配置中心 Spring Cloud Nacos详解之集群配置 Spring Cloud Eureka详解 Spring Cloud Frign详解 Spring Cloud Ribbon详解

    2024年02月12日
    浏览(24)
  • springcloud3 GateWay章节-Eureka+gateway动态路由负载均衡1

    gateway相当于所有服务的门户,将客户端请求与服务端应用相分离,客户端请求通过gateway后由定义的路由和断言进行转发,路由代表需要转发请求的地址,断言相当于请求这些地址时所满足的条件,只有同时符合路由和断言才给予转发 gateWay是微服务的API网关,能够实现服务的

    2024年02月12日
    浏览(28)
  • springcloud3 GateWay章节-Nacos+gateway动态路由负载均衡4

    1.pom文件 2.启动类 3.配置文件 1.启动nacos,sleuth 2.启动gatewayapi,mscloud-nacos-provider7001,mscloud-nacos-provider7002 如图: 3.访问 多次刷新:7001和7002 不停的切换

    2024年02月11日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包