微服务中的网关

  • Post author:
  • Post category:其他




微服务中的网关



1.什么是网关?


⭐️ 网关 = 路由转发 + 过滤器

Gateway (Service Gateway)服务网关,可以统一服务入口,可方便实现对凭他众多服务接口进行管控。


  • 路由转发:接收一切外界请求,转发到后端的微服务上去;

  • 在服务网关中可以完成一系列的横切功能,例如权限校验、限流以及监控等,这些都可以通过过滤器完成


图解:

(以微服务项目中的网关为例)

在这里插入图片描述

在这里插入图片描述



2.网关的作用

1️⃣ 统一所有微服务的入口

2️⃣ 网关可以实现请求路由转发(router dispatcher)以及请求过程负载均衡。

3️⃣ 网关统一服务入口,可方便实现对平台众多服务接口进行管控,对访问服务的身份认证、防报文重放与防数据篡改、功能调用的业务鉴权、响应数据的脱敏、流量与并发控制,甚至基于API调用的计量或者计费等等。


例如做验证,或者屏蔽一些脏话,我们微服务模块中有许多模块都需要这个功能,我们就可以去网关做。



3.SpringCloud提供的网关组件


  • Netflix zuull.x (效率)

  • spring cloud gateway组件 (WebFlux 异步非阻塞IO模型)



4.Gateway组件的使用


提供了一个在springmvc之上构建API网关的库。springcloudgateway旨在提供一种简单而有效的方法来路由到api,并为api提供横切关注点,比如:安全性、监控/度量和弹性。


1.开发springboot应用



2.引入网关依赖

<dependencies>

        <!--引入springboot 网关中不能使用springmvc 的web模型-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-web</artifactId>-->
        <!--</dependency>-->
        <!--引入consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!--引入actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


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

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>


    </dependencies>


3.编写配置

spring:
  cloud:
    gateway:
      routes: 
        - id: teacher_router #路由对象唯一标识
          uri: http:localhost:8787#服务地址
          redicates: #断言用来配置路由规则
           - Path=/teacher
		- id: student_router
          uri: http://localhost:8788
          redicates: #断言用来配置路由规则
           - Path=/student

这个时候我们就可以直接访问网关的服务器,用

xxx/student

来访问8788,或者用

xxx/teacher

访问8787。达到路由转发的目的。



版权声明:本文为Ares___原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。