【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关

简介: 【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(七)Spring Cloud Gateway服务网关

1、GateWay概述

zuul停更了

gateway之所以性能号,因为底层使用WebFlux,而webFlux底层使用netty通信(NIO)

SpringCloud Gateway使用的是Webflux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架

2、GateWay的特性:

Gateway能干什么?

  • 反向代理
  • 鉴权
  • 流量控制
  • 熔断
  • 日志监控

3、GateWay与zuul的区别:

4、zuul1.x的模型:

5、什么是webflux:

是一个非阻塞的web框架,类似springmvc这样的

6、GateWay三大概念:

6.1,路由:

路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由

就是根据某些规则,将请求发送到指定服务上

6.2,断言:

参考的是Java8的java.util.function.Predicate 开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由

就是判断,如果符合条件就是xxxx,反之yyyy

6.3,过滤:

指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改.

路由前后,过滤请求

7、GateWay的工作原理:

Gateway的核心逻辑:路由转发+执行过滤器

下章开始配置一个gateway网关。

8、使用GateWay:

8.1,建module

新建一个GateWay的模块项目

名字: Cloud-gateway-9527

8.2,修改pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud2023</artifactId>
        <groupId>com.tigerhhzz.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Cloud-gateway-9527</artifactId>
    <dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--Springboot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--Springboot actuator-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.tigerhhzz.springcloud-tigerhhzz</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- 引入lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 引入srpingboot test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
8.3,写配置文件
server:
  port: 9527
spring:
  application:
    name: cloud-gateway-service
eureka:
  instance:
    hostname: cloud_gateway_service
  client:
    service-url:
      defaultZone: http://www.eureka7001.com:7001/eureka/
    register-with-eureka: true
    fetch-registry: true
8.4,主启动类
package com.tigerhhzz.springcloud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@Slf4j
public class GateWayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GateWayMain9527.class,args);
        log.info("GateWayMain9527启动成功~~~~~~~~~~~~~~~~~~~");
    }
}
8.5,针对pay模块,设置路由:

我们目前不想暴露8001端口,希望在8001外面套一层9527

cloud-provider-payment8001看看controller的访问地址(两个controller 分别是如下)

@GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }
  @GetMapping(value = "/payment/{id}")
  public CommonResult getPaymentById(@PathVariable("id")Long id){
      Payment result = paymentService.getPaymentById(id);
      log.info("****查询结果:" + result);
      if(result != null){
          return new CommonResult(200, "查询成功,serverPort:  "+serverPort, result);
      }
      return new CommonResult(400, "没有对应id的记录", null);

**修改GateWay模块(9527)的配置文件:

server:
  port: 9527
spring:
  application:
    name: cloud-gateway-service
  cloud:
    gateway:
      routes: #多个路由
        - id: payment_routh                       #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001   #匹配后提供服务的路由地址
          #uri: lb://cloud-payment-service         #路由的ID,没有固定规则但要求唯一,建议配合服务名
          predicates: #断言
            - Path=/payment/**                #断言 路径相匹配的进行路由
        - id: payment_routh2
          uri: http://localhost:8001
          #uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**
            #- After=2022-06-16T19:49:30.417+08:00[Asia/Shanghai]
            #- Cookie=username,tigerhhzz
eureka:
  instance:
    hostname: cloud_gateway_service
  client:
    service-url: //服务提供者provider注册进eureka服务中心
      defaultZone: http://www.eureka7001.com:7001/eureka/
    register-with-eureka: true
    fetch-registry: true

这里表示,

当访问localhost:9527/payment/31时,

路由到localhost:8001/payment/31

8.6,开始测试

启动Cloud-eureka-server7001

启动Cloud-provider-payment8001

启动Cloud-gateway-9527

如果启动GateWay报错
        可能是GateWay模块引入了web和监控的starter依赖,需要移除

访问:

添加网关前:http://localhost:8001/payment/1

添加网关后:http://localhost:9527/payment/1

9、GateWay的网关配置,

Gateway网关路由有两种配置方式:

  • 在配置文件yaml中配置
  • 代码中注入RouteLocator的Bean

GateWay的网关配置,除了支持配置文件,还支持硬编码方式

9.1 使用硬编码配置GateWay:

自己写一个:通过9527网关访问到外网的百度和腾讯网站

创建配置类:

package com.tigerhhzz.springcloud.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GateWayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route",r->r.path("/baidunews").uri("https://news.baidu.com/"));
        return routes.build();
    }
    @Bean
    public RouteLocator customRouteLocator2(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route1",r->r.path("/tencent").uri("https://www.tencent.com/"));
        return routes.build();
    }
}
9.2 重启服务 测试
9.3 通过服务名实现动态路由

上面的配置虽然首先了网关,但是是在配置文件中写死了要路由的地址

现在需要修改,不指定地址,而是根据微服务名字进行路由,我们可以在注册中心获取某组微服务的地址

默认情况下Gatway会根据注册中心注册的服务列表, 以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能

需要注意的是uri的协议lb,表示启用Gateway的负载均衡功能.

lb://serverName是spring cloud gatway在微服务中自动为我们创建的负载均衡uri

需要:

一个eureka7001+两个服务提供者8001/8002

9.3.1 修改GateWay模块的配置文件:
server:
  port: 9527
spring:
  application:
    name: cloud-gateway-service
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes: #多个路由
        - id: payment_routh                       #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-provider-service         #路由的ID,没有固定规则但要求唯一,建议配合服务名
          predicates: #断言
            - Path=/payment/**                #断言 路径相匹配的进行路由
        - id: payment_routh2
          #uri: http://localhost:8001
          uri: lb://cloud-provider-service
          predicates:
            - Path=/payment/lb/**
            #- After=2022-06-16T19:49:30.417+08:00[Asia/Shanghai]
            #- Cookie=username,tigerhhzz
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url: #服务提供者provider注册进eureka服务中心
      defaultZone: http://localhost:7001/eureka/
    register-with-eureka: true
    fetch-registry: true
9.3.2 然后就可以启动微服务.测试

8001/8002两个端口切换 http://localhost:9527/payment/lb

9.3.3 Pridicate断言:

我们之前在配置文件中配置了断言:

这个断言表示,如果外部访问路径是指定路径,就路由到指定微服务上

可以看到,这里有一个Path,这个是断言的一种,断言的类型:

After:
        可以指定,只有在指定时间后,才可以路由到指定微服务
• 1
• 2

这里表示,只有在2020年的2月21的15点51分37秒之后,访问才可以路由

在此之前的访问,都会报404

如何获取当前时区?**

import java.time.ZonedDateTime;
/**
 * @author tigerhhzz
 * @date 2023/4/17 17:10
 */
public class T2 {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println(now);
        //2023-04-17T17:11:53.743+08:00[Asia/Shanghai]
    }
}
before:
        与after类似,他说在指定时间之前的才可以访问
        between:
        需要指定两个时间,在他们之间的时间才可以访问

cookie:
        只有包含某些指定cookie(key,value),的请求才可以路由

利用curl访问测试:

yml中加上:

- Cookie=username,tigerhhzz

curl测试:

Header:
        只有包含指定请求头的请求,才可以路由

测试:

host:
        只有指定主机的才可以访问,
        比如我们当前的网站的域名是www.aa.com
        那么这里就可以设置,只有用户是www.aa.com的请求,才进行路由

可以看到,如果带了域名访问,就可以,但是直接访问ip地址.就报错了

method:
        只有指定请求才可以路由,比如get请求...

path:
        只有访问指定路径,才进行路由
        比如访问,/abc才路由

Query:
        必须带有请求参数才可以访问

9.3.4 Filter过滤器:

生命周期:

在请求进入路由之前,和处理请求完成,再次到达路由之前

种类:

GateWayFilter,单一的过滤器

与断言类似,比如闲置,请求头,只有特定的请求头才放行,反之就过滤:

GlobalFilter,全局过滤器:

自定义过滤器:

实现两个接口

package com.tigerhhzz.springcloud.filter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
@Component
public class MyGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("**************come in MylogGateWayGilter:  " + new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null) {
            System.out.println("********用户名为空,非法用户。");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
}

然后启动服务,即可,因为过滤器通过@COmponet已经加入到容器了

相关实践学习
部署高可用架构
本场景主要介绍如何使用云服务器ECS、负载均衡SLB、云数据库RDS和数据传输服务产品来部署多可用区高可用架构。
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
目录
相关文章
|
12天前
|
Cloud Native Java 关系型数据库
【阿里云云原生专栏】构建云原生应用:基于Spring Boot与阿里云服务的全栈指南
【5月更文挑战第21天】构建云原生应用是企业数字化转型的关键,本文提供了一份基于Spring Boot和阿里云的全栈指南。涵盖从阿里云账号注册、ECS与Docker搭建,到Spring Boot项目创建、业务代码编写和部署。此外,还介绍了如何集成阿里云OSS存储、RDS数据库服务以及ACK容器服务,助力打造高效、可扩展和易管理的云原生应用。
137 3
|
16天前
|
架构师 网络协议 算法
Android高级架构师整理面试经历发现?(大厂面经+学习笔记(1)
Android高级架构师整理面试经历发现?(大厂面经+学习笔记(1)
|
18天前
|
消息中间件 Java RocketMQ
Spring Cloud RocketMQ:构建可靠消息驱动的微服务架构
【4月更文挑战第28天】消息队列在微服务架构中扮演着至关重要的角色,能够实现服务之间的解耦、异步通信以及数据分发。Spring Cloud RocketMQ作为Apache RocketMQ的Spring Cloud集成,为微服务架构提供了可靠的消息传输机制。
30 1
|
18天前
|
Dubbo Java 应用服务中间件
Spring Cloud Dubbo: 微服务通信的高效解决方案
【4月更文挑战第28天】在微服务架构的发展中,服务间的高效通信至关重要。Spring Cloud Dubbo 提供了一种基于 RPC 的通信方式,使得服务间的调用就像本地方法调用一样简单。本篇博客将探讨 Spring Cloud Dubbo 的核心概念,并通过具体实例展示其在项目中的实战应用。
25 2
|
18天前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
|
18天前
|
Java API Nacos
第十二章 Spring Cloud Alibaba Sentinel
第十二章 Spring Cloud Alibaba Sentinel
36 0
|
18天前
|
存储 前端开发 Java
第十一章 Spring Cloud Alibaba nacos配置中心
第十一章 Spring Cloud Alibaba nacos配置中心
33 0
|
18天前
|
消息中间件 SpringCloudAlibaba Java
第十章 SpringCloud Alibaba 之 Nacos discovery
第十章 SpringCloud Alibaba 之 Nacos discovery
13 1
|
18天前
|
NoSQL Java 关系型数据库
【Redis系列笔记】分布式锁
分布式锁:满足分布式系统或集群模式下多进程可见并且互斥的锁。 分布式锁的核心思想就是让大家都使用同一把锁,只要大家使用的是同一把锁,那么我们就能锁住线程,不让线程进行,让程序串行执行,这就是分布式锁的核心思路
309 2
|
5天前
|
存储 NoSQL 算法
Redis (分布式锁)
Redis (分布式锁)
183 0