• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Spring Cloud Alibaba 温故而知新四SpringCloud Gateway 第二代微服务网关

武飞扬头像
eddie_k2
帮助1

目录

7.1.1 第二代微服务网关组件 - Gateway

7.1.1.1 Gateway 核心概念

  • 认识 SpringCloud Gateway 是什么?
    • SpringCloud Gateway 是 Spring 官方最新推出的一款基于 SpringFramework 5,Project Reactor 和 SpringBoot 2 之上的开发网关
    • 它与第一代网关 Zuul 不同的是:Gateway 是异步非阻塞的(Netty WebFlux 实现);Zuul是同步阻塞请求的有数据证明 Gateway 比 Zuul 快了 1.6 倍
    • Gateway 三大组成部分
      • Route路由
        • ID
        • 目标URL
      • Predicate断言
      • Filter过滤器

7.1.1.2 Gateway 工作模型

  • Gateway 工作模型图示以及解读
    • 请求发送到网关,经由分发器将请求匹配到相应的 HandlerMapping
    • 请求和处理器之间有一个映射,路由到网关处理程序,即 Web Handler
    • 执行特定的请求过滤器链
    • 最终到达代理的微服务

如图所示:
学新通

7.2.1 谓词Predicate的原理与应用

7.2.1.1 谓词Predicate是什么

  • 认识 Predicate
    • 首先要先知道 Java 8 引入,位于 java.util.function 包下,是一个 FunctionalInterface(函数式接口)
package java.util.function;

// ...

@FunctionalInterface
public interface Predicate<T> {
   

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     * 
     * 1、返回 boolean  类型
     * 2、test 方法名
     * 3、(T t)需要输入一个参数
     * 4、 通常用在 stream 的 filter 中,表示是否满足过滤条件
     */
    boolean test(T t);

	// ...
}
学新通

7.2.1 谓词Predicate的原理与应用

创建子工程:sca-commerce-gateway

7.2.1.1 Maven 依赖

<?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>sca-commerce</artifactId>
        <groupId>com.edcode.commerce</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sca-commerce-gateway</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!-- 模块名及描述信息 -->
    <name>sca-commerce-gateway</name>
    <description>Spring Cloud Gateway</description>

    <dependencies>
        <!-- spring cloud alibaba nacos discovery 依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!-- 不能引入 spring-boot-starter-web 否则会报错,所以不直接引入 sca-commerce-mvc-config 的子项目-->
        <dependency>
            <groupId>com.edcode.commerce</groupId>
            <artifactId>sca-commerce-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <!--
        SpringBoot的Maven插件, 能够以Maven的方式为应用提供SpringBoot的支持,可以将
        SpringBoot应用打包为可执行的jar或war文件, 然后以通常的方式运行SpringBoot应用
     -->
    <build>
        <finalName>${artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
学新通

7.2.1.2 bootstrap.yml

server:
  port: 9001
  servlet:
    context-path: /edcode

spring:
  application:
    name: sca-commerce-gateway
  cloud:
    nacos:
      # 服务注册发现
      discovery:
        enabled: true # 如果不想使用 Nacos 进行服务注册和发现, 设置为 false 即可
        #server-addr: ${NACOS_ADDR:127.0.0.1}:8848
        server-addr: ${
   NACOS_ADDR_1:127.0.0.1}:8848,${
   NACOS_ADDR_2:127.0.0.1}:8849,${
   NACOS_ADDR_3:127.0.0.1}:8850 # Nacos 服务器地址
        namespace: ${
   NAMESPACE_ID:1adcfdd8-5763-4768-9a15-9c7157988950}
        metadata:
          management:
            context-path: ${
   server.servlet.context-path}/actuator
    # 静态路由
  #    gateway:
  #      routes:
  #        - id: path_route # 路由的ID
  #          uri: 127.0.0.1:8080/user/{id} # 匹配后路由地址
  #          predicates: # 断言, 路径相匹配的进行路由
  #            - Path=/user/{id}
  main:
    allow-bean-definition-overriding: true  # 因为将来会引入很多依赖, 难免有重名的 bean

# 暴露端点
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

学新通

7.2.1.3 创建网关启动入口

package com.edcode.commerce;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description 网关启动入口
 */
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(GatewayApplication.class, args);
    }
}
学新通

7.2.1.4 单元测试

验证工程搭建的正确性测试用例
package com.edcode.commerce;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description 验证工程搭建的正确性测试用例
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class GatewayApplicationTests {
   

    @Test
    public void contextLoad() {
   

    }
}
学新通
Java8 Predicate 使用方法与思想
package com.edcode.commerce.service;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description Java8 Predicate 使用方法与思想
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class PredicateTest {
   

    public static List<String> MICRO_SERVICE = Arrays.asList(
            "nacos", "authority", "gateway", "ribbon", "feign", "hystrix", "sca-commerce"
    );

    /**
     * test 方法主要用于参数符不符合规则, 返回值是 boolean
     * */
    @Test
    public void testPredicateTest() {
   

        Predicate<String> letterLengthLimit = s -> s.length() > 5;
        MICRO_SERVICE.stream().filter(letterLengthLimit).forEach(System.out::println);
    }

    /**
     * and 方法等同于我们的逻辑与 &&, 存在短路特性, 需要所有的条件都满足
     * */
    @Test
    public void testPredicateAnd() {
   

        Predicate<String> letterLengthLimit = s -> s.length() > 5;
        Predicate<String> letterStartWith = s -> s.startsWith("gate");

        MICRO_SERVICE.stream().filter(
                letterLengthLimit.and(letterStartWith)
        ).forEach(System.out::println);
    }

    /**
     * or 等同于我们的逻辑或 ||, 多个条件主要一个满足即可
     * */
    @Test
    public void testPredicateOr() {
   

        Predicate<String> letterLengthLimit = s -> s.length() > 5;
        Predicate<String> letterStartWith = s -> s.startsWith("gate");

        MICRO_SERVICE.stream().filter(
                letterLengthLimit.or(letterStartWith)
        ).forEach(System.out::println);
    }

    /**
     * negate 等同于我们的逻辑非 !
     * */
    @Test
    public void testPredicateNegate() {
   

        Predicate<String> letterStartWith = s -> s.startsWith("gate");
        MICRO_SERVICE.stream().filter(letterStartWith.negate()).forEach(System.out::println);
    }

    /**
     * isEqual 类似于 equals(), 区别在于: 先判断对象是否为 NULL,
     * 不为 NULL 再使用 equals 进行比较
     * */
    @Test
    public void testPredicateIsEqual() {
   

        Predicate<String> equalGateway = s -> Predicate.isEqual("gateway").test(s);
        MICRO_SERVICE.stream().filter(equalGateway).forEach(System.out::println);
    }

}
学新通

7.4.1 集成 Alibaba Nacos 实现动态路由配置

7.4.1.1 静态路由配置与动态路由配置

  • 静态路由配置
    • 静态路由配置写在配置文件(yml 或 properties 文件中),端点是:spring.cloud.gateway
    • 缺点非常明显,每次改动都需要网关模块重新部署
spring:
  application:
    name: sca-commerce-gateway
  cloud:
    # 静态路由
      gateway:
        routes:
          - id: path_route # 路由的ID
            uri: 127.0.0.1:8080/user/{
   id} # 匹配后路由地址
            predicates: # 断言, 路径相匹配的进行路由
              - Path=/user/{
   id}
  • 动态路由配置
    • 路由信息在 Alibaba Nacos 中维护,可以实现动态变更

学新通

7.4.1.2 Nacos 配置列表

  • Data ID: sca-commerce-gateway-router
  • Group: sca-commerce
  • 配置内容:
[
    {
   
        "id"<

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggbkjf
系列文章
更多 icon
同类精品
更多 icon
继续加载