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