Spring Cloud Alibaba 快速学习之 Gateway

news2024/9/21 0:30:13

1 引言

Gateway顾名思义就是“网关”的意思,旨在为微服务提供统一的访问入口,然后转发到各个微服务,通常可以在网关中统一做安全认证、监控、限流等等功能,避免每个微服务都重复实现这些功能。

2 代码

本章演示的项目基于Spring Cloud Alibaba 快速学习之 Nacos中的项目进行迭代,源码链接在文章末尾列出。

新增三个子项目:gateway、gateway-order、gateway-user
在这里插入图片描述

  • 父级pom.xml
<?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>org.example</groupId>
    <artifactId>spring-cloud-alibaba-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>server-a</module>
        <module>user-a</module>
        <module>server-b</module>
        <module>rocketmq-producer</module>
        <module>rocketmq-consumer-a</module>
        <module>rocketmq-consumer-b</module>
        <module>gateway</module>
        <module>gateway-user</module>
        <module>gateway-order</module>
    </modules>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--  为Spring Boot项目提供一系列默认的配置和依赖管理-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.2</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!--  Spring Boot核心-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- Spring Boot单元测试和集成测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot构建Web应用程序-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

</project>

2.1 gateway

提供网关服务
在这里插入图片描述
1 gateway/pom.xml

<?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>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>spring-cloud-alibaba-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>gateway</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>


    <dependencies>

        <!-- Nacos 服务发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2023.0.1.2</version>
        </dependency>
        <!-- gateway 网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>4.1.5</version>
        </dependency>
        <!-- spring cloud 负载均衡-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
            <version>4.1.4</version>
        </dependency>

    </dependencies>


</project>

2 gateway/src/main/resources/application.yml

server:
  port: 8070
spring:
  application:
    name: gateway-server
  main:
    web-application-type: reactive #解决和spring-boot-starter-web冲突
  cloud:
    nacos:
      config:
        serverAddr: 127.0.0.1:8848 #nacos服务地址
    gateway:
      globalcors: # 全局的跨域处理
        cors-configuration:
        '[/**]':
          allowCredentials: true
          allowedOrigins: "*"
          allowedMethods: "*"
          allowedHeaders: "*"
      routes: # 路由配置
        - id: id1
          uri: lb://gateway-order # 对应的nacos服务名称
          predicates: # 断言规则
            - Path=/order/**
        - id: id2
          uri: lb://gateway-user
          predicates:
            - Path=/user/**

点击查看更多断言规则
在这里插入图片描述

3 gateway/src/main/java/org/example/MainGateway.java

package org.example;

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

@EnableDiscoveryClient //spring cloud开启服务发现功能
@SpringBootApplication
public class MainGateway {

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

}

4 gateway/src/main/java/org/example/conf/GatewayGlobalFilter.java
这个类就是gateway全局过滤器,安全认证等功能可以在这里实现。

package org.example.conf;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 */
@Component
public class GatewayGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("url:" + path);

        return chain.filter(exchange);
    }
}

2.2 gateway-order

提供测试接口服务
在这里插入图片描述

1 gateway-order/pom.xml

<?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>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>spring-cloud-alibaba-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>gateway-order</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <!-- Nacos 服务发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2023.0.1.2</version>
        </dependency>

    </dependencies>

</project>

2 gateway-order/src/main/resources/application.yml

server:
  port: 8071
spring:
  application:
    name: gateway-order
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848 #nacos服务地址

3 gateway-order/src/main/java/org/example/MainGatewayOrder.java

package org.example;

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

@EnableDiscoveryClient //spring cloud开启服务发现功能
@SpringBootApplication
public class MainGatewayOrder {

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

}

4 gateway-order/src/main/java/org/example/controller/TestController.java

package org.example.controller;

import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/order")
public class TestController {


    private static final String serverName = "this is gateway-order";

    @GetMapping("/get")
    public String get() {
        return serverName;
    }


    @GetMapping("/get/{string}")
    public String get(@PathVariable String string) {
        return serverName + ":" + string;
    }


}

2.3 gateway-user

提供测试接口服务
在这里插入图片描述

1 gateway-user/pom.xml

<?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>
    <parent>
        <groupId>org.example</groupId>
        <artifactId>spring-cloud-alibaba-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>gateway-user</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <!-- Nacos 服务发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2023.0.1.2</version>
        </dependency>

    </dependencies>

</project>

2 gateway-user/src/main/resources/application.yml

server:
  port: 8072
spring:
  application:
    name: gateway-user
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848 #nacos服务地址

3 gateway-user/src/main/java/org/example/MainGatewayUser.java

package org.example;

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

@EnableDiscoveryClient //spring cloud开启服务发现功能
@SpringBootApplication
public class MainGatewayUser {

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

}

4 gateway-user/src/main/java/org/example/controller/TestController.java

package org.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class TestController {


    private static final String serverName = "this is gateway-user";

    @GetMapping("/get")
    public String get() {
        return serverName;
    }


    @GetMapping("/get/{string}")
    public String get(@PathVariable String string) {
        return serverName + ":" + string;
    }


}

3 测试

1,启动nacos,在分别启动三个子项目。然后访问nacos控制台:http://192.168.31.220:8848/nacos/index.html,可以看到三个项目都已注册。
在这里插入图片描述2,打开浏览器访问:http://localhost:8070/user/get,可以看到被转发到了gateway-user的/user/get接口。
在这里插入图片描述
在这里插入图片描述3,打开浏览器访问:http://localhost:8070/order/get,可以看到被转发到了gateway-order的/order/get接口。
在这里插入图片描述

在这里插入图片描述

4 源码

Gitee代码链接

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2094873.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何使用MabatisPlus

一. 引入相关的Maven依赖 例如下面我所引用的依赖 <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency>二.将写好的mapper继承BaseMap…

ref 和 reactive 区别

前言 ref 和 reactive是Vue 3中响应式编程的核心。在Vue中&#xff0c;响应式编程是一种使数据与UI保持同步的方式。当数据变化时&#xff0c;UI会自动更新&#xff0c;反之亦然。这种机制大大简化了前端开发&#xff0c;使我们能够专注于数据和用户界面的交互&#xff0c;而不…

【Spring】Spring Boot入门(1)

本系列共涉及4个框架&#xff1a;Sping,SpringBoot,Spring MVC,Mybatis。 博客涉及框架的重要知识点&#xff0c;根据序号学习即可。 目录 1、什么是Spring 1.1 什么是Spring 1.2 Spring与Spring Boot&#xff08;Spring 脚手架&#xff09;的关系 2、了解Maven 2.1 什…

好用的宠物浮毛清理神器,希喂、IAM、范罗士宠物空气净化器大揭秘

最近宠物空气净化器在养宠家庭中的讨论度一直很高&#xff0c;产品主打可以吸附宠物浮毛和异味的功能。养了三只小猫的我对此也很感兴趣&#xff0c;准备入手一台试试。可我没有想到宠物空气净化器的品牌有这么多&#xff0c;功课都做了好久。看了好几天&#xff0c;最后在希喂…

【Python报错已解决】`SyntaxError: can‘t assign to function call`

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏: 《C干货基地》《粉丝福利》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 文章目录 引言&#xff1a;一、问题描述&#xff1a;1.1 报错示例&#xff1a;1.2 报错分析&#xff1a;1.3 解决思路&#xff…

Quartz任务调度框架

文章目录 前言一、介绍二、使用步骤1.创建maven工程&#xff0c;添加依赖2.创建任务3.启动任务 三、基本实现原理1. Scheduler任务调度器2. Triggers触发器2.1 SimpleTrigger2.2 CronTirgger 3. Misfire策略4 任务Job4.1 Job4.2 JobDetail4.3 JobDataMap 前言 最近跟的一个系统…

洞见数据价值,激活组织活力,让决策更精准的智慧地产开源了

智慧地产视觉监控平台是一款功能强大且简单易用的实时算法视频监控系统。它的愿景是最底层打通各大芯片厂商相互间的壁垒&#xff0c;省去繁琐重复的适配流程&#xff0c;实现芯片、算法、应用的全流程组合&#xff0c;从而大大减少企业级应用约95%的开发成本。通过计算机视觉和…

Sql查询优化--索引设计与sql优化(包含慢查询定位+explain解释计划+左匹配原则+索引失效)

本文介绍了数据库查询的索引优化方法&#xff0c;依次介绍了慢查询语句定位方法、索引设计与sql语句优化方法&#xff0c;并介绍了左匹配原则和索引失效的场景&#xff0c;最后介绍了explain执行计划要怎么看以调整检验索引设计是否生效和效率情况&#xff0c;创新介绍了如何以…

AWS api数据信息获取(boto3)

GitHub - starsliao/TenSunS: &#x1f984;后羿 - TenSunS(原ConsulManager)&#xff1a;基于Consul的运维平台&#xff1a;更优雅的Consul管理UI&多云与自建ECS/MySQL/Redis同步Prometheus/JumpServer&ECS/MySQL/Redis云监控指标采集&Blackbox站点监控维护&漏…

4家国产数据库上市公司:最好的盈利1个亿,最惨亏8000w

目前国产数据库xc目录中大概有11家公司&#xff0c;其中多家公司已经上市了&#xff0c;且公布了最新的半年报&#xff01; 这里尝试分析一下几家国产数据库上市公司的发展潜力和情况。 达梦数据库 达梦数据库作为国产数据库第一股&#xff0c;业绩增长还是一如既往的猛&…

【零知识证明】通读Tornado Cash白皮书(并演示)

1 Protocol description 协议描述有以下功能&#xff1a; 1.insert&#xff1a;向智能合约中存入资金&#xff0c;通过固定金额的单笔交易完成&#xff0c;金额由N表示&#xff08;演示时用1 ETH&#xff09; 2.remove&#xff1a;从智能合约中提取资金&#xff0c;交易由收…

ncnn之yolov5(7.0版本)目标检测pnnx部署

一、pnxx介绍与使用 pnnx安装与使用参考&#xff1a; https://github.com/pnnx/pnnxhttps://github.com/Tencent/ncnn/wiki/use-ncnn-with-pytorch-or-onnxhttps://github.com/Tencent/ncnn/tree/master/tools/pnnx 支持python的首选pip&#xff0c;否则就源码编译。 pip3 …

Webpack打包常见问题及优化策略

聚沙成塔每天进步一点点 本文回顾 ⭐ 专栏简介Webpack打包常见问题及优化策略1. 引言2. Webpack打包常见问题2.1 打包时间过长问题描述主要原因 2.2 打包体积过大问题描述主要原因 2.3 依赖包版本冲突问题描述主要原因 2.4 动态导入和代码拆分问题问题描述主要原因 2.5 文件路径…

C++系列-继承方式

继承方式 继承的语法继承方式&#xff1a;继承方式的特点继承方式的举例 继承可以减少重复的代码。继承允许我们依据另一个类来定义一个类&#xff0c;这使得创建和维护一个应用程序变得更容易。基类父类&#xff0c;派生类子类&#xff0c;派生类是在继承了基类的部分成员基础…

编程效率进阶:打造你专属的 Git 别名与 PyCharm 完美结合

在日常开发中&#xff0c;Git 是我们不可或缺的工具。掌握常用 Git 命令可以帮助我们更高效地进行版本控制&#xff0c;但随着命令的复杂性增加&#xff0c;记住所有命令变得困难。这时&#xff0c;Git 别名的设置就显得尤为重要。此外&#xff0c;许多开发者使用 PyCharm 作为…

【Android自定义控件】Kotlin实现滚动效果的数字加减控件

前言 因业务上的需要&#xff0c;在APP中点餐时要有商品数目增减操作&#xff0c;数目增减的过程中有翻动的动画效果展现。在Android中有多种方式可以实现&#xff0c;本篇文章记录通过自定义View结合控件的平移动画相结合来实现此需求。 需求分析 根据上图分析控件的实现过程以…

Pillow:一个强大的图像处理Python库

我是东哥&#xff0c;一个热衷于探索Python世界的自媒体人。今天&#xff0c;我要向大家介绍一个在Python图像处理领域中不可或缺的库——Pillow。如果你对图像处理感兴趣&#xff0c;或者正在寻找一个简单易用的库来处理图片&#xff0c;那么Pillow绝对是你的不二之选。 基本…

【前端】代码Git提交规范之限制非规范化提交信息

需求背景 在我们目前的前端项目中&#xff0c;我们采用 git 作为版本控制工具。使用 git 管理项目意味着我们经常需要提交代码。当我们执行 git commit -m "描述信息" 命令时&#xff0c;我们被要求提供一个描述信息。现在使用约定式规范提交&#xff0c;和Commitiz…

用纯 div 实现一个选中和未选中状态

在现代网页设计中&#xff0c;利用 div 元素自定义样式&#xff0c;可以让界面更具有吸引力。通过一些简单的 CSS 样式和布局技巧&#xff0c;可以轻松实现交互自然的选中和未选中效果&#xff0c;而不需要依赖传统的 input 元素。 举个 &#x1f330; HTML <body><…

金融POS三层密钥体系 银行卡网络安全系统

银行卡网络安全系统的三层密钥体系 银行卡网络安全系统的三层密钥体系为金融POS系统提供了高度安全的密钥管理。这个体系从上到下分为三层&#xff1a;系统密钥、主密钥、和工作密钥。每一层密钥都负责保护下一层密钥的安全性&#xff0c;确保系统整体的安全性。 三层密钥体系…