Spring Cloud Gateway替代zuul作为API网关(一)

2023-11-15

本文简要介绍如何使用Spring Cloud Gateway 作为API 网关(不是使用zuul作为网关),关于Spring Cloud Gateway和zuul的性能比较本文不再赘述,基本可以肯定Spring Cloud Finchley版本的gateway比zuul 1.x系列的性能和功能整体要好。

特别提醒:Spring Cloud Finchley版本中,即使你引入了spring-cloud-starter-netflix-zuul,也不是2.0版本的zuul

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

我们的介绍分为3个部分, 第一,pom文件,第二项目的基本架构,第三源码和截图。

  • 第一,pom文件

因为使用Eureka作为服务注册和发现,因此在pom中引入了eureka,各位可根据自己的实际情况修改。

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yq</groupId>
    <artifactId>GatewayDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.33</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

    </dependencies>


    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • 第二,项目结构

总共有3个项目,
第一个项目是eureka 注册中心,非常简单,基本就一个Application类。 端口7700
第二个项目是User service,也非常简单提供两个rest api,为了简略不连接数据库,直接在内存中生成一组数据。端口6601
第三个项目就是我们的网关。端口6604

目前项目中集成websocket服务配置,本文暂不介绍可直接忽略。

  • 第三,项目代码和运行截图

网关的主代码

package com.yq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;


@SpringCloudApplication
public class APIGatewayApplication  {
    private static final Logger logger = LoggerFactory.getLogger(APIGatewayApplication.class);

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/baidu")
                        .uri("http://baidu.com:80/")
                )
               .route("websocket_route", r -> r.path("/apitopic1/**")
                .uri("ws://127.0.0.1:6605"))
                .route(r -> r.path("/userapi3/**")
                        .filters(f -> f.addResponseHeader("X-AnotherHeader", "testapi3"))

                        .uri("lb://user-service/")
                )
                .build();
    }

    public static void main(String[] args) {
        SpringApplication.run(APIGatewayApplication.class, args);
        logger.info(" Start APIGatewayApplication Done");
    }

}

网关的配置文件application.yml

server:
  port: 6604


#服务名
spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      filter:
        remove-non-proxy-headers:
          headers:
          - dummy
      routes:
        - id:  apiuser
        # 重点!/info必须使用http进行转发,lb代表从注册中心获取服务
          uri: lb://user-service
          predicates:
          # 重点!转发该路径!,/userapi/**,
          - Path=/userapi/**
          # http://localhost:6601/userapi/user/users/2, 必须加上StripPrefix=1,否则访问服务时会带上userapi
          #而不是我们期望的去掉userapi,只保留**部分
          filters:
          - StripPrefix=1
        - id:  api2user
          uri: lb://user-service
          predicates:
          - Path=/userapi2/**
          filters:
          - StripPrefix=1


eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:7700/eureka/

我们简要分析分析一下配置文件

  • id: apiuser
    # 重点!/info必须使用http进行转发,lb代表从注册中心获取服务
    uri: lb://user-service
    predicates:
    # 重点!转发该路径!,/userapi/,
    - Path=/userapi/

    # http://localhost:6601/userapi/user/users/2, 必须加上StripPrefix=1,否则访问服务时会带上userapi
    #而不是我们期望的去掉userapi,只保留**部分
    filters:
    - StripPrefix=1

配置了一个路由apiuser, 当路径( - Path=/userapi/**),就转发到服务(lb://user-service),同时把路径中的userapi这部分去掉(- StripPrefix=1)。

  • 运行效果图

直接访问User service
http://localhost:6601/user/users/2

通过网关访问user service
http://localhost:6604/userapi/user/users/2

这里写图片描述

参考文档:
1, http://cloud.spring.io/spring-cloud-static/Finchley/single/spring-cloud.html#_spring_cloud_gateway
2, https://github.com/spring-cloud-samples/spring-cloud-gateway-sample

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Cloud Gateway替代zuul作为API网关(一) 的相关文章

随机推荐

  • Python爬虫 XPath解析出乱码 解决方法

    请求后加上编码 resp requests get url headers headers resp encoding GBK
  • Springboot操作Elasticsearch——聚合分组与排序

    这两天项目中需要从es中查询数据 根据某个字段进行分组 求其最大 最小 平均值 并按最大值进行排序 springboot的版本号 2 0 6 RELEASE Elasticsearch的版本号 5 6 3 主要代码记录下 BoolQuery
  • 拆解开源项目Blender

    计划把Blender项目拆解出来 如果把Blender项目比作一辆汽车 那拆解的任务就是把它的发动机 轮胎 支架等不同的模块单独出来并能独自运行 不知道以前有没有人这样干过 在其他项目上 这样拆解的好处是可以更好地研究它的工作原理 并将这些
  • AFNetWorking出现code=-1016错误解决办法

    AFNetWorking的JSON解析默认库是使用的AFJSONRequestOperation模式 只支持text json application json text javascript 所以如果出现code 1016错误则说明当前的
  • 告别2021,迎接2022

    2021相对有点忙有点累 一直想记录一下 但是实在是在惰性趋势下 歇息了一个月 才正常提笔微记 最近思绪也比较忙 提笔规划也是有点凌乱 2021年在新单位的第二年 开始结交朋友 受朋友们的影响 开始准备考研 软考 幸运的是 也都坚持下来了
  • adb将Apk内置到系统中(system/priv-app)

    有时候我们在Android 系统内置自己的应用 在测试时 Android Studio 默认的安装方式是将我们开发的应用作为普通应用安装到系统中的 本文提供一种方式 在开发过程中 将apk内置到系统中 而不需要系统源代码 adb 将apk内
  • java新建一个窗口_Java实例:使用JFram创建一个简单的窗口

    一个图形用户界面以一个top level container开始 它为其他的界面组件提供了一个 家 指定应用程序的总体感觉 在本教程中 向你介绍JFrame类 它将用于给一个Java应用程序创建一个简单的top level窗口 打开你的编辑
  • UI操作 解决方案

    1 include
  • 中断、信号、系统调用

    1 中断的分类 中断程序的方法可以分为硬件中断和软件中断 硬件中断是硬件自动触发的 包括中断和异常 比如 中断 通过中断控制器给CPU的INTR引脚发送信号 如按下键盘 会给CPU一个0x21中断号 异常 CPU执行某条指令发生异常 会自己
  • tr td分合并单元格

    table border 1 width 200 tr td ss td tr tr td width 25 td td width 25 td tr table
  • Spark性能优化:数据倾斜调优

    前言 继 Spark性能优化 开发调优篇 和 Spark性能优化 资源调优篇 讲解了每个Spark开发人员都必须熟知的开发调优与资源调优之后 本文作为 Spark性能优化指南 的高级篇 将深入分析数据倾斜调优与shuffle调优 以解决更加
  • 设计补偿器网络以改善开关频率响应

    直流开关电压转换器 或 开关调节器 控制回路的特点是频率响应 频率响应影响开关调节器的反应时间对瞬态变化 精度和稳定性的影响 并在输入电压 负载和工作周期变化的情况下 如何保持设定的电压输出 工程师可以通过增加补偿器网络来改善开关调节器的频
  • Linux在云服务器上安装JDK

    官网地址下载 Java Downloads Oracle 将下载好的jdk通过Xftp传输到服务器上去 创建一个文件夹用于区分 在home文件夹下创建一个属于自己的文件夹 将需要的文件传输过去 也可以直接在 usr local 下配置 cd
  • win7电脑最新版微信卡死问题的解决

    最近一段时间无论单位还是家里事情都比较多 导致没有时间学习和写文 排名蹭蹭地往下掉 刚好遇到一个win7版微信卡死的问题 在网上查了下 找到了win10相关的可以参考的解决办法 确实有效 在此介绍一下 一 问题现象 当最小化win7托盘的微
  • linux环境安装php fileinfo扩展

    linux环境安装php fileinfo扩展 windows环境安装扩展比较简单 只需要把dll拷贝到扩展目录 修改php ini中相应的扩展就好了 下面来介绍一下linux环境下的php扩展安装 以centos6 5和php7 1为例
  • C++ OpenCV制作九宫格拼图游戏

    学更好的别人 做更好的自己 微卡智享 本文长度为2498字 预计阅读7分钟 前言 上一篇 C OpenCV生成九宫格图像 介绍了如何将图片分割城九宫格 然后重新打乱了顺序显示出来 本篇就来说一下怎么制作一个九宫格的拼图游戏 项目的重新创建了
  • JAVA是什么意思

    JAVA的意思是计算机的编程语言 Java通过面向对象的编程语言 它不仅吸收了C 语言的优点 而且摒弃了C 中难于理解的多继承和指针的概念 具有简单性 功能强大 分布式 健壮性 安全性 平台独立与可移植性 多线程及动态性的特点 Java语言
  • 第二十一课,几何着色器(基础篇)

    几何着色器的作用 输入 输入类型 从顶点着色器接收下列任何一个图元值 类型 数组大小 points 绘制GL POINTS图元时 1 lines 绘制GL LINES或GL LINE STRIP时 2 lines adjacency GL
  • seaborn学习笔记(二):散点图、线图

    html font family sans serif ms text size adjust 100 webkit text size adjust 100 body margin 0 article aside details figc
  • Spring Cloud Gateway替代zuul作为API网关(一)

    本文简要介绍如何使用Spring Cloud Gateway 作为API 网关 不是使用zuul作为网关 关于Spring Cloud Gateway和zuul的性能比较本文不再赘述 基本可以肯定Spring Cloud Finchley版