Spring Cloud 2022.x版本使用gateway和nacos实现动态路由和负载均衡

news2024/9/24 3:27:12

文章目录

    • 1、nacos下载安装
      • 1.1、启动服务器
      • 1.2、关闭服务器
      • 1.3、服务注册&发现和配置管理接口
    • 2、代码示例
      • 2.1、app1工程代码
      • 2.2、app2工程代码
      • 2.3、gateway网关工程代码
    • 3、动态配置网关路由
      • 3.1、配置动态路由
      • 3.2、配置为负载模式
    • 4、gateway配置规则
      • 4.1、请求转发,转发指定地址
      • 4.2、去掉指定的前缀路径
      • 4.3、正则匹配重写路径

Spring Cloud Alibaba官方:https://sca.aliyun.com/zh-cn/
Spring Cloud官网:https://spring.io/projects/spring-cloud

Spring Cloud与Spring Cloud Alibaba版本对应说明:https://sca.aliyun.com/zh-cn/docs/2022.0.0.0/overview/version-explain
在这里插入图片描述
在这里插入图片描述

1、nacos下载安装

下载地址:https://github.com/alibaba/nacos/releases
下载编译压缩并解压:nacos-server-2.2.3.zip。

1.1、启动服务器

注:Nacos的运行需要以至少2C4g60g*3的机器配置下运行。

#启动命令(standalone代表着单机模式运行,非集群模式):

#Linux/Unix/Mac
sh startup.sh -m standalone

#如果您使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:
bash startup.sh -m standalone

#Windows
startup.cmd -m standalone

1.2、关闭服务器

#Linux/Unix/Mac
sh shutdown.sh

#Windows
shutdown.cmd
#或者双击shutdown.cmd运行文件。

1.3、服务注册&发现和配置管理接口

#服务注册
curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'

#服务发现
curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instance/list?serviceName=nacos.naming.serviceName'

#发布配置
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=HelloWorld"

#获取配置
curl -X GET "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test"

参考自官方安装说明:https://nacos.io/zh-cn/docs/quick-start.html

2、代码示例

示例代码分为3个工程:app1(服务1工程),app2(服务2工程),gateway(网关工程),使用的依赖包版本:

com.alibaba.cloud:2022.0.0.0
org.springframework.cloud:2022.0.4
org.springframework.boot:3.0.9

app1,app2都提供个接口:goods(商品信息接口),user(用户信息接口)

goods接口通过网关,app1和app2提供负载模式访问
user接口通过网关,代理方式访问

2.1、app1工程代码

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>com.penngo.app1</groupId>
    <artifactId>gateway-app1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2022.0.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2022.0.4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>3.0.9</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

配置文件:application.yml

spring:
  application:
    name: app-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        locator:
          lower-case-service-id: true
server:
  port: 9091
  servlet:
    encoding:
      force: true
      charset: UTF-8
      enabled: true

业务代码:AppMain.java

package com.penngo.app1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@EnableDiscoveryClient
public class AppMain {
    public static void main(String[] args) {
        SpringApplication.run(AppMain.class, args);
    }

    @RestController
    public class HelloController {
        @GetMapping("/goods")
        public Map goods(){
            Map<String, String> data = new HashMap<>();
            data.put("name", "手机");
            data.put("service", "app1");
            return data;
        }
        @GetMapping("/user")
        public Map<String, String> user(){
            Map<String, String> data = new HashMap<>();
            data.put("user", "test");
            data.put("service", "app1");
            return data;
        }
    }
}

在这里插入图片描述

2.2、app2工程代码

pom.xml与app1工程一样。
配置文件:application.yml,与app2区分不同的端口

spring:
  application:
    name: app-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        locator:
          lower-case-service-id: true
server:
  port: 9091
  servlet:
    encoding:
      force: true
      charset: UTF-8
      enabled: true

在这里插入图片描述

2.3、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>

    <groupId>com.penngo.gateway</groupId>
    <artifactId>gateway-nacos</artifactId>
    <version>1.0-SNAPSHOT</version>
    <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>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2022.0.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2022.0.4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>3.0.9</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

配置application.yml

server:
  port: 9090
spring:
  application:
    name: gatewayapp
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        locator:
          lower-case-service-id: true
      config:
        server-addr: localhost:8848
        # 加载 dataid 配置文件的后缀,默认是 properties
        file-extension: yml
        # 配置组,默认就是 DEFAULT_GROUP
        group: DEFAULT_GROUP
        # 配置命名空间,此处写的是 命名空间的id 的值,默认是 public 命名空间
        # namespace:
        # data-id 的前缀,默认就是 spring.application.name 的值
        prefix: ${spring.application.name}

GatewayMain.java

package com.penngo.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

3、动态配置网关路由

三个工程启动后,nacos的服务列表

在这里插入图片描述

3.1、配置动态路由

spring:
  cloud:
    gateway:
      routes:
        - id: app1
          uri: http://localhost:9091/
          predicates:
            - Path=/app1/**
          filters:
            - StripPrefix=1
        - id: app2
          uri: http://localhost:9092/
          predicates:
            - Path=/app2/**
          filters:
            - StripPrefix=1

配置后,可以通过网关的端口9090和地址访问

http://localhost:9090/app1/user
http://localhost:9090/app2/user

在这里插入图片描述

在这里插入图片描述

3.2、配置为负载模式

spring:
  cloud:
    gateway:
      routes:
        - id: app1
          uri: http://localhost:9091/
          predicates:
            - Path=/app1/**
          filters:
            - StripPrefix=1
        - id: app2
          uri: http://localhost:9092/
          predicates:
            - Path=/app2/**
          filters:
            - StripPrefix=1
        - id: app
          uri: lb://app-service
          predicates:
            - Path=/app/**
          filters:
            - StripPrefix=1

配置后,可以通过同一个地址访问到两个服务返回的数据

http://localhost:9090/app/goods

在这里插入图片描述
在这里插入图片描述

4、gateway配置规则

参数说明

id: 路由ID
uri: 目标地址,可以是服务,如果服务Spring推荐用全大写,实际调用大小写不敏感,都可以调通。
predicates: 匹配路径,以浏览器请求的端口号后面的第一级路径为起始。
filters: 过滤器,包含Spring Gateway 内置过滤器,可以自定义过滤器。

4.1、请求转发,转发指定地址

routes:
# 跳转URL
- id: 163_route
  uri: http://localhost:9091/
  predicates:
    - Path=/app
  • 访问地址:http://localhost:9090/app/index
  • 真实地址:http://localhost:9091/app/index

4.2、去掉指定的前缀路径

- id: app1
  uri: http://localhost:9091/
  predicates:
    - Path=/app1/**
  filters:
    - StripPrefix=1

去掉第1层的路径前缀app1

  • 访问地址:http://localhost:9090/app1/user
  • 真实地址:http://localhost:9091/user

4.3、正则匹配重写路径

- id: test
  uri: lb://app-service
  predicates:
    - Path=/test/**
  filters:
    - RewritePath=/test/(?<path>.*), /$\{path}

去掉第1层的路径前缀app1

  • 访问地址:http://localhost:9090/app/goods
  • 真实地址:http://localhost:9091/goods 或 http://localhost:9091/goods

源码下载

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

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

相关文章

PADS layout 使用记录-封装name

1. 元件封装添加位号等标签 pads layout中封装的name不见了&#xff0c;好久不知道怎么添加回来&#xff0c;终于找到了“添加新标签” 按钮&#xff1a; 点击之后&#xff0c;在这里直接设置就好了

RK3588开发板编译环境Ubuntu20.04编译配置增加交换内存

迅为提供的编译环境 Ubuntu20.04 默认配置了交换内存是 9G&#xff0c;如果在编译过程中&#xff0c;因内 存不够而编译报错&#xff0c;可以参考本小节进行设置。 这里举例分配 5G 交换内存。 在开始之前&#xff0c;使用命令检查一下您的 ubuntu 的 swap 分区。 sudo swa…

DataFun:推荐系统峰会

工程架构与训练推理 TFDE 多场景多目标融合 企业知识推荐系统 ATA内部社区 房产推荐场景的算法实践

智驾算力芯片市场仍处于「波动」周期,Momenta曝光自研NPU

用「冷热不均」来形容当下的汽车芯片赛道&#xff0c;再合适不过了。 本周&#xff0c;英伟达公布的第二财季&#xff08;5-7月&#xff09;营收达到创纪录的135亿美元&#xff0c;大幅超出了此前市场普遍预期的略高于110亿美元&#xff0c;同比增速更是达到了101%。 其中&…

AIGC人工智能涉及三十六职业,看看有没有你的职业(二)

文章目录 如何生成IP盲盒 设计儿童节海报 制作商用矢量插画 设计徽章 图片融合 后缀参数 Stylize 风格化 赛博朋克头像 中国风瓷娃娃 生成线稿 制作时尚音乐唱片封面 T恤图案设计-告白气球 引领时尚潮流的服装设计之旅 独一无二的包包奇迹 手机壳设计探险 如何生…

c#写的端口监听,程序退出后,再次运行提示端口占用,且进程不存在

我用c#写了一个监听29999端口,进程结束后再次启动发现端口被占用&#xff0c;但是运行netstat -ano | findstr 29999找到进程ID后&#xff0c;却没有这个进程 经查询这个监听29999进程虽然没了&#xff0c;但是要找到他的父进程&#xff0c;把父进程关闭了才可以&#xff0c;参…

骨传导耳机值得入手吗?盘点最值得入手的几款骨传导耳机

无线耳机最近一两年越来越受欢迎&#xff0c;市场上不同形态的耳机品类让人眼花缭乱&#xff0c;从骨传导&#xff0c;夹耳式到气传导等等都有&#xff0c;尤其是不用入耳佩戴的耳机&#xff0c;不伤耳朵&#xff0c;佩戴更舒适更安全&#xff0c;而骨传导耳机可以说是近几年来…

c++中i++和++i的区别

结论 1. i 是两步操作&#xff0c;第一步&#xff1a;a i 第二步&#xff1a;i i1&#xff0c;最终返回a&#xff0c;但a是不具名的&#xff0c;也无法取地址 2. i 也是两步操作&#xff0c;第一步&#xff1a;i i1 第二步&#xff1a;return i&#xff0c;最终返回…

pywebview 通过 JSBridge 调用 TTS

pip install pywin32 ; pip install pywebview ; 通过 JSBridge 调用本机 TTS pip install cefpython3 cefpython3-66.1-py2.py3-none-win_amd64.whl (69.0 MB) Successfully installed cefpython3-66.1 编写 pywebview_tts.py 如下 # -*- coding: utf-8 -*- ""&…

vscode | 开发神器vscode自定义用户代码片段

目录 一、增加二、删除三、语法四、变量 一、增加 点击&#xff1a;左下角设置齿轮按钮——>用户代码片段 点击&#xff1a;新建全局代码片段文件 输入文件名 会出现如下界面 配置以下语句 "cls": {"scope": "javascript,typescript",…

(学习笔记-调度算法)磁盘调度算法

磁盘结构&#xff1a; 常见的机械磁盘是上图左边的样子&#xff0c;中间圆的部分是磁盘的盘片&#xff0c;一般会有多个盘片&#xff0c;每个盘面都有自己的磁头。右边的图就是一个盘片的结构&#xff0c;盘片中的每一层分为多个磁道&#xff0c;每个磁道分为多个扇区&#xff…

C++:命名空间,缺省参数,函数重载,引用,内联函数

个人主页 &#xff1a; 个人主页 个人专栏 &#xff1a; 《数据结构》 《C语言》《C》 文章目录 前言一、命名空间命名空间的定义命名空间的使用 二、缺省参数缺省参数概念缺省参数分类 三、函数重载函数重载的概念 四、引用引用的概念引用特性引用的使用场景引用与指针的区别 …

【中危】Spring Kafka 反序列化漏洞 (CVE-2023-34040)

zhi.oscs1024.com​​​​​ 漏洞类型反序列化发现时间2023-08-24漏洞等级中危MPS编号MPS-fed8-ocuvCVE编号CVE-2023-34040漏洞影响广度小 漏洞危害 OSCS 描述Spring Kafka 是 Spring Framework 生态系统中的一个模块&#xff0c;用于简化在 Spring 应用程序中集成 Apache Kaf…

【C++心愿便利店】No.2---函数重载、引用

文章目录 前言&#x1f31f;一、函数重载&#x1f30f;1.1.函数重载概念&#x1f30f;1.2.C支持函数重载的原理 -- 名字修饰 &#x1f31f;二、引用&#x1f30f;2.1.引用的概念&#x1f30f;2.2.引用特性&#x1f30f;2.3.常引用&#x1f30f;2.4.使用场景&#x1f30f;2.5.传…

Llama-2大模型本地部署研究与应用测试

最近在研究自然语言处理过程中&#xff0c;正好接触到到大模型&#xff0c;特别是在年初chatgpt引来的一大波AIGC热潮以来&#xff0c;一直都想着如何利用大模型帮助企业的各项业务工作&#xff0c;比如智能检索、方案设计、智能推荐、智能客服、代码设计等等&#xff0c;总得感…

CSS内边距和外边距属性

外边距属性用margin&#xff1b;padding属性叫填充&#xff0c;或者也叫内边距&#xff1b; margin:标签与标签的距离&#xff0c;到包围它的元素的边框的距离&#xff1b; padding&#xff1a;内边距&#xff0c;用于控制内容与边框之间的距离&#xff1b; CSS padding&…

Spring Boot(Vue3+ElementPlus+Axios+MyBatisPlus+Spring Boot 前后端分离)【三】

&#x1f600;前言 本篇博文是关于Spring Boot(Vue3ElementPlusAxiosMyBatisPlusSpring Boot 前后端分离)【三】的分享&#xff0c;希望你能够喜欢 &#x1f3e0;个人主页&#xff1a;晨犀主页 &#x1f9d1;个人简介&#xff1a;大家好&#xff0c;我是晨犀&#xff0c;希望我…

【力扣每日一题】2023.8.26 汇总区间

目录 题目&#xff1a; 示例&#xff1a; 分析&#xff1a; 代码&#xff1a; 题目&#xff1a; 示例&#xff1a; 分析&#xff1a; 题目给我们一个有序数组&#xff0c;让我们把数组内的元素汇总区间&#xff0c;也就是说有一串数字是连续的&#xff0c;比如是 1 2 3 4…

数据结构:线性表之-顺序表

目录 1.线性表概念 1.1 什么是顺序列表 1.2 线性表 2.顺序表实现 将有以下功能&#xff1a; 详细过程 顺序表的动态存储 顺序表初始化 尾插 扩容 头插 更改后的尾插 尾删 头删 打印 释放内存 优化顺序表 (任意位置插入删除) 优化后的头插尾插 优化后的头删尾…

npm常用命令 + 前端常用的包管理工具 以及 npm淘宝镜像配置等

npm常用命令 前端常用的包管理工具 以及 npm淘宝镜像配置等 1. 前言1.1 NodeJs的下载安装1.2 windows上1.3 常用包管理工具 2. npm2.1 npm 的安装2.2 npm初始化包2.3 npm 安装、卸载包2.3.1 非全局安装2.3.1.1 单个包的安装2.3.1.1.1 默认版本安装2.3.1.1.2 指定版本安装 2.3.…