SpringCloud2022.x集成gateway

news/2024/11/24 7:07:45/

SpringCloud2022.x集成gateway

  • 1、环境依赖
  • 2、项目代码
    • 2.1、新建springboot项目
      • 2.1.1、修改pom.xml
      • 2.1.2、修改启动类
      • 2.1.3、修改配置文件
      • 2.1.4、nacos创建配置
      • 2.1.5、新增自定义路由配置类
      • 2.1.6、新增打印日志过滤器
      • 2.1.7、启动测试

文档内容:

  • 整合gateway网关
  • 使用Nacos进行配置管理
  • 使用Nacos进行服务注册

1、环境依赖

  • JDK 17+
  • mysql 8.x
  • Nacos 2.2.0+
  • SpringBoot 3.x
  • SpringCloud 2022.0.0
  • SpringCloud Alibaba 2022.0.0.0-RC1

2、项目代码

2.1、新建springboot项目

2.1.1、修改pom.xml

父模块的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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.hippo</groupId><artifactId>java-study</artifactId><version>0.0.1-SNAPSHOT</version><name>${project.artifactId}</name><packaging>pom</packaging><description>java学习包</description><modules><module>study-commons</module><module>study-gateway</module><module>study-servies</module></modules><properties><java.version>17</java.version><!-- 修改项目的目标jdk --><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><maven.compiler.compilerVersion>17</maven.compiler.compilerVersion><!-- 静态资源编码 --><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><!-- 项目编码 --><file.encoding>UTF-8</file.encoding></properties><dependencyManagement><dependencies><!-- springboot-dependencies --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>3.0.0</version><type>pom</type><scope>import</scope></dependency><!-- spring-cloud-dependencies --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>2022.0.0</version><type>pom</type><scope>import</scope></dependency><!-- spring-cloud-alibaba-dependencies --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2022.0.0.0-RC1</version><type>pom</type><scope>import</scope></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version><scope>provided</scope></dependency><!-- mongodb --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>2.3.9.RELEASE</version></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><!-- htool工具包 --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId><version>5.8.11</version></dependency><!-- mybatis-plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- study-commons公共包 --><dependency><groupId>com.hippo</groupId><artifactId>mongodb</artifactId><version>0.0.1-SNAPSHOT</version></dependency><dependency><groupId>com.hippo</groupId><artifactId>swagger2</artifactId><version>0.0.1-SNAPSHOT</version></dependency><dependency><groupId>com.hippo</groupId><artifactId>swagger3</artifactId><version>0.0.1-SNAPSHOT</version></dependency><!-- swagger2.x需要引入两个jar包 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><!-- swagger 3.x只需要引入一个jar包 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency><!-- swagger增强ui --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency><!--  swagger-ui 增强版 前身是是swagger-bootstrap-ui  --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><!-- jasypt实现账号密码加密解密 --><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.2</version></dependency><!-- Json处理工具fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><scope>compile</scope><version>1.2.83_noneautotype</version></dependency></dependencies></dependencyManagement><build></build></project>

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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.hippo</groupId><artifactId>java-study</artifactId><version>0.0.1-SNAPSHOT</version><relativePath>../pom.xml</relativePath> <!-- lookup parent from repository --></parent><artifactId>study-gateway</artifactId><name>${project.artifactId}</name><description>gateway网关</description><properties><java.version>17</java.version></properties><dependencies><!--  gateway  --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- Nacos配置中心依赖  --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!-- Nacos 发现以进行服务注册/发现依赖  --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- 负载均衡  --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency><!-- SpringCloud-2020.X.X以后版本官方重构了bootstrap引导配置的加载方式,需要添加以下依赖 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><!-- lombok  --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- hutools  --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.hippo.database.DataBaseApplication</mainClass><skip>false</skip></configuration></plugin></plugins></build></project>

2.1.2、修改启动类

添加注解@EnableDiscoveryClient

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.hippo</groupId><artifactId>java-study</artifactId><version>0.0.1-SNAPSHOT</version><relativePath>../pom.xml</relativePath> <!-- lookup parent from repository --></parent><artifactId>study-gateway</artifactId><name>${project.artifactId}</name><description>gateway网关</description><properties><java.version>17</java.version></properties><dependencies><!--  gateway  --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- Nacos配置中心依赖  --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!-- Nacos 发现以进行服务注册/发现依赖  --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- 负载均衡  --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency><!-- SpringCloud-2020.X.X以后版本官方重构了bootstrap引导配置的加载方式,需要添加以下依赖 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency><!-- lombok  --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!-- hutools  --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.hippo.database.DataBaseApplication</mainClass><skip>false</skip></configuration></plugin></plugins></build></project>

2.1.3、修改配置文件

注意:如果使用使用bootstrap.properties或者bootstrap.yaml,需要加入spring-cloud-starter-bootstrap依赖,这里使用bootstrap.yaml
当然你可以不使用bootstrap.yaml,你可以配置spring.config.import: optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}进行配置nacos需要导入的配置。

spring:application:name: gatewayprofiles:active: testhost: 175.178.17.15cloud:nacos:discovery:server-addr: ${spring.host:127.0.0.1}:8848namespace: 29c504c4-0aa0-4a13-b487-5fddad0356f7config:serverAddr:  ${spring.host:127.0.0.1}:8848file-extension: yaml#        shared-configs: # 共享配置#            - dataId: gateway-dev.yaml#              group: DEFAULT_GROUP#              refresh: truenamespace: 29c504c4-0aa0-4a13-b487-5fddad0356f7gateway:discovery:locator:enabled: true # 开启服务发现routes:- id: 数据操作 # 路由iduri: lb://database # 服务名predicates:- Path=/database/** # 路径匹配filters:- StripPrefix=1 # 去掉前缀#  # 导入nacos配置
#  config:
#    # 因为springboot 2.4版本以后默认关闭加载bootstrap.yml,所以只能通过此方式连接到nacos config
#    import: optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}management:endpoint:health:show-details: alwaysendpoints:web:exposure:include: '*'
logging:level:com.alibaba.cloud.nacos.configdata: debug

2.1.4、nacos创建配置

nacos访问地址:http://XXX.XXX.XXX.XXX:8848/nacos

Data ID:gateway-test.yaml
Group:DEFAULT_GROUP
描述:xxxxx
配置格式:YAML
配置内容:

server: port: 9000spring: cloud: gateway: discovery: locator: enabled: true # 路由配置        routes: - id: 数据操作 uri: lb://database predicates: - Path=/database/** filters: - StripPrefix=1 

发布

2.1.5、新增自定义路由配置类

新建RouteLocatorConfig

package com.hippo.studygateway.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;/*** @ClassName RouteLocatorConfig* @Description TODO 自定义网关路由配置* @Author tangxl* @create 2023-03-27 14:19**/
@Configuration
public class RouteLocatorConfig {@Beanpublic RouteLocator routeLocator(RouteLocatorBuilder routeLocator){RouteLocatorBuilder.Builder routes = routeLocator.routes();return routes.route("path_route1", r -> r.path("/guonei").uri("http://news.baidu.com/guonei"))  //说明:访问localhost:9527/guonei地址会转发到http://news.baidu.com/guonei地址.route("path_route2",r->r.path("/guoji").uri("https://news.baidu.com/guoji")).route("path_route3",r->r.path("/gateway").uri("https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/")).route(p->p.path("/lb/**") //lb: 请求地址中必须包含lb.filters(f->f.stripPrefix(1)) //去掉第一个路径.uri("lb://cloud-payment-service") //lb: 负载均衡指向地址).build();}
}

2.1.6、新增打印日志过滤器

package com.hippo.studygateway.filter;import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.time.LocalDate;
import java.util.Date;/*** @ClassName GatewayLogFilter* @Description TODO 拦截日志类* @Author tangxl* @Date 2022/7/14 9:38**/
@Component
@Slf4j
public class LogGlobalFilter implements GlobalFilter, Ordered {//问题:无法注入Bean,需要手动将过滤器加载到容器中
//    @Autowired
//    private SystemFeignService systemFeignService;@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("LogGlobalFilter日志记录:"+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
//        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
//        if (uname == null) {
//            log.info("************用户名为空!");
//            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//            return exchange.getResponse().setComplete();
//        }String reqPath = exchange.getRequest().getPath().toString();String reqParams = exchange.getRequest().getQueryParams().toString();String reqBodys = exchange.getRequest().getBody().toString();log.info("请求路径:"+reqPath);log.info("params参数:"+reqParams);log.info("body参数:"+reqBodys);
//        systemFeignService.saveInterfaceLog("接口路径"+reqPath);return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;}
}

2.1.7、启动测试

浏览器输入:http://localhost:9000/database/config/get

显示:nacos-config-1.0


http://www.ppmy.cn/news/37381.html

相关文章

C# 实例详解委托之Func、Action、delegate

委托是.NET编程的精髓之一&#xff0c;在日常编程中经常用到&#xff0c;在C#中实现委托主要有Func、Action、delegate三种方式&#xff0c;这个文章主要就这三种委托的用法通过实例展开讲解。 【Func】&#xff1a;Func是带返回值的委托&#xff1a; 原型函数如下(以下展示的…

2023美赛春季赛F题思路数据代码论文分享

文章目录赛题思路赛题详情参赛建议&#xff08;个人见解&#xff09;选择队友及任务分配问题&#xff08;重要程度&#xff1a;5星&#xff09;2023美赛春季赛F题思路数据代码【最新】赛题思路 (赛题出来以后第一时间在CSDN分享) 最新进度在文章最下方卡片&#xff0c;加入获取…

数据库:关系数据库标准语言SQL(一)

终于开始实战了&#xff0c;首先我这里是下载的SQL server&#xff0c;因为oracle和SQLserver的部分语法不同&#xff0c;所以本文出现的代码可能在oracle中报错 一、了解SQL语言的特色 SQL的特点 综合统一&#xff1a;SQL语言集数据定义语言DDL、数据操纵语言DML、数据控制语…

C语言 —— 数组

一维数组与二维数组前言一、 一维数组1.1 一维数组定义和使用1.2 例子 &#xff1a;列出0-9的数字1.3 一维数组的初始化1.4 数组名二、二维数组2.1 二维数组的定义2.2 例题&#xff1a;一个学习小组有 5 个人&#xff0c;每个人有 3 门课程的考试成绩&#xff0c;求该小组各科的…

Android车载系统(HVAC) 原理+源码分析(代码示例)

前言 Android车载系统&#xff08;HVAC&#xff09;是一种用于控制车内温度、空气质量和湿度的系统&#xff0c;它是一项重要的汽车电子技术。在这种系统中&#xff0c;CarHvacManager控制器是一个重要的组件&#xff0c;它通过与车载传感器和执行器的通信来控制车内环境。 C…

资深工程师带你了解IC工程师级别与薪资

入行IC之后&#xff0c;想必大家更关心的就是工程师薪资和级别&#xff0c;因为入行的大多数也是工程师。 国际的一流企业基本上工程师分为以下几个级别&#xff1a;普通工程师&#xff0c;资深工程师&#xff0c;主管工程师&#xff0c;资深主管&#xff0c;总工, 资深总工&am…

考pmp有什么好处?

PMP证书报名条件要求高&#xff0c;这是众所周知的事&#xff0c;那你通过了PMP考试&#xff0c;就证明你是有一定能力的&#xff0c;重要的是&#xff0c;你已经有了至少半年的项目管理经验&#xff0c;并且在你申请考试的前六年内&#xff0c;累计项目管理达三年。 PMP有什么…

Java学习星球,Java学习路线

目录一、Java学习路线二、学习计划三、为何会有Java学习星球&#xff1f;四、加入星球后&#xff0c;你可以得到什么&#xff1f;五、如何加入Java学习星球&#xff1f;六、打卡挑战大家好&#xff0c;我是哪吒&#xff0c;一个靠着热情攀登至C站巅峰的中年男子&#xff0c;CSD…