Commit a2392223 by 林冲

初始化项目

0 parents
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="gsc-gateway" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="gsc-gateway" options="-parameters" />
</option>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="central" />
<option name="url" value="http://192.168.3.233/nexus/content/groups/public" />
</remote-repository>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="temurin-17" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="svn" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="6dd290ef-5416-4e2c-8ef6-02093e7e62f0" name="Changes" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectColorInfo"><![CDATA[{
"associatedIndex": 6
}]]></component>
<component name="ProjectId" id="32pBYWXUMUj7WWS63YLYY598llH" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"last_opened_file_path": "D:/files/java/development/mySpace/demo/gsc-master-v1",
"project.structure.last.edited": "Project",
"project.structure.proportion": "0.0",
"project.structure.side.proportion": "0.0",
"settings.editor.selected.configurable": "project.propVCSSupport.DirectoryMappings"
}
}]]></component>
<component name="RunManager">
<configuration name="GscMain" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="com.gsc4cloud.gsc.gateway.GscMain" />
<module name="gsc-gateway" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="com.gsc4cloud.gsc.gateway.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.GscMain" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="SvnConfiguration" cleanupOnStartRun="true">
<configuration>C:\Users\Sandul\AppData\Roaming\Subversion</configuration>
<supportedVersion>125</supportedVersion>
</component>
<component name="SvnFileUrlMappingImpl">
<option name="myMappingRoots">
<list>
<SvnCopyRootSimple>
<option name="myVcsRoot" value="D:\files\java\development\workspace_scrm\gsc\trunk\src\gsc-gateway" />
<option name="myCopyRoot" value="D:\files\java\development\workspace_scrm\gsc\trunk\src\gsc-gateway" />
</SvnCopyRootSimple>
</list>
</option>
<option name="myMoreRealMappingRoots">
<list>
<SvnCopyRootSimple>
<option name="myVcsRoot" value="D:\files\java\development\workspace_scrm\gsc\trunk\src\gsc-gateway" />
<option name="myCopyRoot" value="D:\files\java\development\workspace_scrm\gsc\trunk\src\gsc-gateway" />
</SvnCopyRootSimple>
</list>
</option>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="6dd290ef-5416-4e2c-8ef6-02093e7e62f0" name="Changes" comment="" />
<created>1758107682829</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1758107682829</updated>
</task>
<task id="LOCAL-00001" summary="优化判断">
<option name="closed" value="true" />
<created>1758115959957</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1758115959957</updated>
</task>
<option name="localTasksCounter" value="2" />
<servers />
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="优化判断" />
<option name="LAST_COMMIT_MESSAGE" value="优化判断" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
FROM registry.cn-hangzhou.aliyuncs.com/dockerhub_mirror/java:21-anolis
WORKDIR /gsc-gateway
ARG JAR_FILE=target/gsc-gateway.jar
COPY ${JAR_FILE} app.jar
EXPOSE 9999
ENV TZ=Asia/Shanghai JAVA_OPTS="-Xms128m -Xmx256m -Djava.security.egd=file:/dev/./urandom"
CMD sleep 60; java $JAVA_OPTS -jar app.jar
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2020 gsc4cloud Authors. All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>com.gsc4cloud</groupId>
<artifactId>gsc</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>gsc-gateway</artifactId>
<packaging>jar</packaging>
<description>gsc 服务网关,基于 spring cloud gateway</description>
<dependencies>
<!--gateway 网关依赖,内置webflux 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<!--注册中心客户端-->
<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>
<!-- LB 扩展 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<!--caffeine 替换LB 默认缓存实现-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<!-- 工具包依赖 -->
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-common-core</artifactId>
</dependency>
<!--接口文档-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
</dependency>
<!--引入Knife4j的官方ui包-->
<dependency>
<groupId>io.springboot</groupId>
<artifactId>knife4j-openapi3-ui</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.fabric8</groupId>
<artifactId>docker-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
# 广联GSC(glsk spring cloud)开发规范
## 一、技术栈选型约束
| 层级 | 技术组件 | 版本要求 | 说明 |
|-------|----------------------|------------------------------|--------------------------------------------|
| 基础环境 | JDK | openJDK 17 | 统一JDK版本,避免因版本差异导致的兼容性问题 |
| | Spring Boot | 3.5.x | 遵循LTS版本,兼容Spring Cloud Alibaba 2025.0.x及以上 |
| | Spring Cloud Alibaba | 2025.0.x | 提供注册中心、配置中心等核心能力 |
| 注册与配置 | Nacos | 3.0.x | 作为注册中心(服务发现)和配置中心(动态配置) |
| 内部通信 | Feign | Spring Cloud OpenFeign 4.3.x | 声明式HTTP客户端 |
| 数据存储 | Druid | 1.2.x | 数据库连接池,提供监控、慢SQL分析能力 |
| ORM | MyBatis-Plus | 3.5.x | 基于MyBatis扩展,简化CRUD操作 |
| 日志 | Logback | 1.5.x | 统一日志框架,输出结构化日志(JSON格式) |
| 消息中间件 | RabbitMQ | RabbitMQ 3.7.x | 异步解耦,支持事务消息 |
| 数据库 | MySQL | MySQL 8.0+ | 关系型数据库 |
| 缓存 | Redis | spring data redis 3.5.x | 分布式缓存 |
| | Redisson | | redis分布式操作开源客户端 |
| 工具包 | hutool | 5.8.38 | |
| 文件上传 | 阿里云OSS | | 使用广联的alioss封装组件 |
## 二、部署方案
### 1. 广联OPS集成打包部署(推荐)
由运维将项目集成至OPS打包部署和版本管理
### 2. 使用docker进行打包部署
此脚手架支持docker打包部署
### 3. 快速开始参考
[开发]快速开始·语雀
## 三、开发规范
### 1. 代码分层及项目结构规范
#### 1.1 对外API facade项目结构
#### 1.2 服务层biz项目结构
### 2. 接口设计规范
#### 2.1 协议与格式
- 内部服务调用:HTTP/REST(Feign)
- 入参/出参:RESTful风格
#### 2.2 接口命名
- 根据id详情查询:`项目名.模块名.功能.detail.by.id`
- 根据参数列表分页查询:`项目名.模块名.功能.page.by.condition`
- 根据参数列表查询:`项目名.模块名.功能.list.by.condition`
- 保存:`项目名.模块名.功能.save`
- 根据id更新:`项目名.模块名.功能.update.by.id`
示例:
```
# admin项目,sys模块,dict功能,根据id查询详情
admin.sys.dict.detail.by.id
```
### 3. Feign客户端规范
```java
@FeignClient(
name = "user-service", // 必填,服务名
contextId = "userApiClient", // 必填,客户端唯一标识
path = "/api/v1" // 可选,接口统一前缀
)
public interface UserApiClient {
// 接口方法
}
```
### 4. MyBatis-Plus规范
#### CRUD操作:
```java
// 正确示例:查询有效订单(status=1)
QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("status",1).orderByDesc("create_time");
List<Order> orders=orderMapper.selectList(queryWrapper);
```
### 5. 依赖管理规范
- 禁止循环依赖
- 版本统一通过gps parent管理
## 四、组件使用及配置模板
### 1. 应用配置
#### 本地配置:`application.yml`
#### Nacos配置中心配置:
- 网关配置:`gsc-gateway-dev.yml`
- 后台项目配置:`gsc-upms-biz-dev.yml`
- 对接前端项目配置:`gsc-upms-biz-dev.yml`
### 2. Nacos服务注册发现配置
开发Nacos地址:
`http://192.168.3.102:8868/nacos/`
账密:`nacos/nacos`
### 3. 数据库及Druid连接池配置
```yaml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
url: jdbc:mysql://192.168.3.227:3306/dj_smartcarlife?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
username: dev_admin
password: 1f7e1ed2
driver-class-name: com.mysql.cj.jdbc.Driver
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: admin@123
```
### 4. Redis及Redisson配置
```yaml
spring:
data:
redis:
host: 192.168.3.226
port: 6379
database: 0
timeout: 30000
redisson:
config:
singleServerConfig:
idleConnectionTimeout: 10000
connectTimeout: 5000
timeout: 3000
```
### 5. XXL-JOB配置
```yaml
xxl:
job:
admin:
addresses: http://192.168.1.124:8080/xxl-job-admin
accessToken: default_token
timeout: 3
executor:
appname: @artifactId@-executor
address: http://192.168.1.207:9999,http://192.168.1.124:9999
port: 9999
logpath: /data/applogs/项目名/jobhandler
logretentiondays: 30
```
### 6. RabbitMQ配置
```java
// 高可靠性最佳实践
public void sendWithFullReliability(String exchange,String routingKey,String content){
rabbitTemplate.setConfirmCallback((correlation,ack,reason)->{
if(!ack){
log.error("Message nacked: {}",reason);
}
});
rabbitTemplate.convertAndSend(exchange,routingKey,content,message->{
MessageProperties props=message.getMessageProperties();
props.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
props.setHeader("retryCount",0);
props.setExpiration("600000"); // 10分钟后过期
return message;
});
}
```
### 7. 阿里云OSS配置
```yaml
gsc:
alioss:
enabled: true
bucket-pool:
jinrong-huidan-test:
enable-intranet: true
access-key-id: LTAI5*************F2fk4e
access-key-secret: iYJdlgs6*************Ck83d5C
endpoint: oss-cn-shenzhen.aliyuncs.com
region: cn-shenzhen
```
### 8. 雪花算法配置
```yaml
gsc:
common:
snowflake:
enabled: true
```
### 9. 分布式锁配置
```xml
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-common-lock</artifactId>
<version>1.0.0</version>
</dependency>
```
## 五、示例代码
### 阿里云OSS上传示例
```java
@Autowired
private AliOssUploadClient aliOssUploadClient;
@Test
public void testAliOssUploadFile(){
String objectName="testdev/wKgFDWcZuYWAS1VBAAvF0oY4U7A75.webp";
String filePath="D:\\test\\bhg-图片\\wKgFDWcZuYWAS1VBAAvF0oY4U7A75.webp";
String bucketName="jinrong-huidan-test";
File file=new File(filePath);
String fileUrl=aliOssUploadClient.uploadFileSimple(bucketName,objectName,file,null);
System.out.println(fileUrl);
}
```
### 雪花ID生成示例
```java
@Autowired
private SnowflakeWorker snowflakeWorker;
@Test
public void testSnowflake(){
long currentId=snowflakeWorker.nextId();
System.out.println(currentId);
}
```
# 关于跨域
```yaml
经过网关联调:
http://网关ip:端口/调用项目/路径
直连服务
http://服务ip:端口/路径
```
\ No newline at end of file \ No newline at end of file
/*
* Copyright (c) 2020 gsc4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gsc4cloud.gsc.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 网关应用
*
* @author
* @date 2025/07/18
*/
@EnableDiscoveryClient
@SpringBootApplication
public class GscMain {
public static void main(String[] args) {
SpringApplication.run(GscMain.class, args);
}
}
package com.gsc4cloud.gsc.gateway.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gsc4cloud.gsc.gateway.filter.WebRequestSignFilter;
import com.gsc4cloud.gsc.gateway.filter.GscRequestGlobalFilter;
//import com.gsc4cloud.gsc.gateway.filter.SignGatewayFilter;
import com.gsc4cloud.gsc.gateway.handler.GlobalExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 网关配置类
*
* @author lengleng
* @date 2025/05/30
*/
@Configuration(proxyBeanMethods = false)
public class GatewayConfiguration {
/**
* 创建gscRequest全局过滤器
* @return gscRequest全局过滤器
*/
@Bean
public GscRequestGlobalFilter gscRequestGlobalFilter() {
return new GscRequestGlobalFilter();
}
/**
* 创建签名过滤器
* @return
*/
@Bean
public WebRequestSignFilter cacheRequestBodyFilter() {
return new WebRequestSignFilter();
}
/**
* 创建全局异常处理程序
* @param objectMapper 对象映射器
* @return 全局异常处理程序
*/
@Bean
public GlobalExceptionHandler globalExceptionHandler(ObjectMapper objectMapper) {
return new GlobalExceptionHandler(objectMapper);
}
}
/*
* Copyright (c) 2020 gsc4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gsc4cloud.gsc.gateway.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;
import java.util.Objects;
/**
* 路由限流配置类
*
* @author lengleng
* @date 2019/2/1
*/
@Configuration(proxyBeanMethods = false)
public class RateLimiterConfiguration {
/**
* 创建基于远程地址的KeyResolver实例
* @return 根据请求的远程地址生成限流key的KeyResolver
* @see <a href=
* "https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-requestratelimiter-gatewayfilter-factory">Spring
* Cloud Gateway文档</a>
*/
@Bean
public KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono
.just(Objects.requireNonNull(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()))
.getAddress()
.getHostAddress());
}
}
package com.gsc4cloud.gsc.gateway.config;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Map;
/**
* @Description 签名属性配置
* @Author yelq
* @Date 2025/7/28-19:09
* @Version 1.0
*/
@ToString
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.cloud.gateway.sign")
public class SignConfigProperties {
// 密钥对
private Map<String, String> KayPairs;
// 排除路径,具体路径
private List<String> excludedPath;
// 排除路径,包含路径
private List<String> excludedContainPath;
// 排除路径,正则匹配路径
private List<String> excludedRegexPath;
// 默认过期时间五分钟
private Long requestTimeout = 5 * 60 * 1000L;
}
package com.gsc4cloud.gsc.gateway.config;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.properties.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Configuration;
import java.util.Set;
import java.util.stream.Collectors;
/**
* SpringDoc配置类,实现InitializingBean接口,用于Swagger 3.0文档展示
*
* @author lengleng
* @date 2025/05/30
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(value = "springdoc.api-docs.enabled", matchIfMissing = true)
public class SpringDocConfiguration implements InitializingBean {
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
private final DiscoveryClient discoveryClient;
/**
* 在初始化后调用的方法,用于注册SwaggerDocRegister订阅器
*/
@Override
public void afterPropertiesSet() {
NotifyCenter.registerSubscriber(new SwaggerDocRegister(swaggerUiConfigProperties, discoveryClient));
}
}
/**
* Swagger文档注册器,用于处理服务实例变更事件并更新Swagger UI配置
*
* @author lengleng
* @date 2025/05/30
*/
@RequiredArgsConstructor
class SwaggerDocRegister extends Subscriber<InstancesChangeEvent> {
private final SwaggerUiConfigProperties swaggerUiConfigProperties;
private final DiscoveryClient discoveryClient;
/**
* 处理服务实例变更事件
* @param event 服务实例变更事件对象
*/
@Override
public void onEvent(InstancesChangeEvent event) {
Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> swaggerUrlSet = discoveryClient.getServices()
.stream()
.flatMap(serviceId -> discoveryClient.getInstances(serviceId).stream())
.filter(instance -> StringUtils.isNotBlank(instance.getMetadata().get("spring-doc")))
.map(instance -> {
AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
swaggerUrl.setName(instance.getServiceId());
swaggerUrl.setUrl(String.format("/%s/v3/api-docs", instance.getMetadata().get("spring-doc")));
return swaggerUrl;
})
.collect(Collectors.toSet());
swaggerUiConfigProperties.setUrls(swaggerUrlSet);
}
/**
* 订阅类型方法,返回订阅的事件类型
* @return 订阅的事件类型
*/
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
}
}
/*
* Copyright (c) 2020 gsc4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gsc4cloud.gsc.gateway.filter;
import com.gsc4cloud.gsc.common.core.constant.CommonConstants;
import com.gsc4cloud.gsc.common.core.constant.SecurityConstants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
/**
* 全局拦截器,作用于所有微服务
* <p>
* 1. 清洗请求头中的from参数 2. 重写StripPrefix = 1,支持全局路由
*
* @author lengleng
* @date 2025/05/30
*/
public class GscRequestGlobalFilter implements GlobalFilter, Ordered {
/**
* 处理Web请求并(可选地)通过给定的网关过滤器链委托给下一个过滤器
*
* @param exchange 当前服务器交换对象
* @param chain 提供委托给下一个过滤器的方式
* @return {@code Mono<Void>} 表示请求处理完成
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
httpHeaders.remove(SecurityConstants.FROM);
// 设置请求时间
httpHeaders.put(CommonConstants.REQUEST_START_TIME,
Collections.singletonList(String.valueOf(System.currentTimeMillis())));
}).build();
// 2. 重写StripPrefix
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L)
.collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
}
@Override
public int getOrder() {
return 10;
}
}
/*
* Copyright (c) 2020 gsc4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gsc4cloud.gsc.gateway.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gsc4cloud.gsc.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* 网关异常通用处理器,作用于WebFlux环境,优先级低于ResponseStatusExceptionHandler
*
* @author lengleng
* @date 2025/05/30
*/
@Slf4j
@Order(-1)
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
/**
* 对象映射器,用于JSON序列化与反序列化
*/
private final ObjectMapper objectMapper;
/**
* @param exchange 服务器网络交换对象
* @param ex 抛出的异常
* @return Mono<Void> 异步处理结果
*/
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
ServerHttpResponse response = exchange.getResponse();
if (response.isCommitted()) {
return Mono.error(ex);
}
// header set
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if (ex instanceof ResponseStatusException) {
response.setStatusCode(((ResponseStatusException) ex).getStatusCode());
}
return response.writeWith(Mono.fromSupplier(() -> {
DataBufferFactory bufferFactory = response.bufferFactory();
try {
log.error("错误具体信息:",ex);
log.debug("Error Spring Cloud Gateway : {} {}", exchange.getRequest().getPath(), ex.getMessage());
return bufferFactory.wrap(objectMapper.writeValueAsBytes(R.failed(ex.getMessage())));
}
catch (JsonProcessingException e) {
log.error("Error writing response :", ex);
return bufferFactory.wrap(new byte[0]);
}
}));
}
}
package com.gsc4cloud.gsc.gateway.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
/**
* @Description 签名工具类
* @Author yelq
* @Date 2025/7/29-11:10
* @Version 1.0
*/
@Slf4j
public class SignUtil {
/**
* 生成签名
* @param params 请求参数
* @param secret 应用密钥
* @return 签名值
*/
public static String generateSign(Map<String, Object> params, String secret) {
// 1. 参数排序
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
// 2. 拼接参数
StringBuilder sb = new StringBuilder();
for (String key : keys) {
if ("X-Sign".equals(key) || params.get(key)==null|| "".equals(params.get(key))) {
continue;
}
sb.append(key).append("=").append(params.get(key)).append("&");
}
String stringToSign = sb.toString();
stringToSign = stringToSign + "secret=" + secret;
// 3. 计算HMAC-SHA256签名
return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret).hmacHex(stringToSign);
}
/**
* 验证签名
* @param params 请求参数
* @param secret 应用密钥
* @return 是否验证通过
*/
public static boolean verifySign(Map<String, Object> params, String secret) {
if (secret==null|| secret.isEmpty()){
log.info("秘钥为空!");
return false;
}
String sign = (String) params.get("X-Sign");
if (StringUtils.isEmpty(sign)) {
return false;
}
return sign.equals(generateSign(params, secret));
}
public static void main(String[] args) {
Map<String, Object> params = new HashMap<>();
params.put("X-App-Id", "dj_zhixin");
long l = System.currentTimeMillis();
System.out.println(l);
params.put("X-Timestamp", l+"");
params.put("X-Nonce", "123456");
params.put("id", "6");
params.put("objs", "[\"hehe\", \"haah\"]");
// params.put("objs", "haah");
// params.put("sessionId", "8b476c7d-6dbb-4059-aab3-5eb75988d2b4");
String sign = generateSign(params, "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b");
System.out.println(sign);
params.put("X-Sign", sign);
System.out.println(verifySign(params, "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b"));
}
}
server:
# 服务端口
port: 9898
spring:
application:
# 应用名称,取pom文件中的artifactId
name: @artifactId@
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: @nacos.username@
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: @nacos.password@
# nacos注册中心
discovery:
# 命名空间id(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: nacos3.beta.glsx.com:8848
# 启用监控功能
watch:
enabled: true
# 设置监控间隔为1000毫秒(即1秒)
watch-delay: 1000
config:
# 命名空间(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos配置服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${spring.cloud.nacos.discovery.server-addr}
# 配置文件
config:
# 配置文件导入
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
file:
file:
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
server:
# 服务端口
port: 9898
spring:
application:
# 应用名称,取pom文件中的artifactId
name: @artifactId@
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: @nacos.username@
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: @nacos.password@
# nacos注册中心
discovery:
# 命名空间id(必须使用命名空间id)
namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${NACOS_HOST:192.168.3.102}:${NACOS_PORT:8868}
# 启用监控功能
watch:
enabled: true
# 设置监控间隔为1000毫秒(即1秒)
watch-delay: 1000
config:
# 命名空间(必须使用命名空间id)
namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos配置服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${spring.cloud.nacos.discovery.server-addr}
# 配置文件
config:
# 配置文件导入
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
file:
path: /data/java_log/jetty/${spring.application.name}
level:
root: debug
server:
# 服务端口
port: 9898
spring:
application:
# 应用名称,取pom文件中的artifactId
name: @artifactId@
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: gsc-biz-user
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: WEqj#2weGlsx123d_@#2!0f2
# nacos注册中心
discovery:
# 命名空间id(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: nacos3.release.glsx.com:8838
# 启用监控功能
watch:
enabled: true
# 设置监控间隔为1000毫秒(即1秒)
watch-delay: 1000
config:
# 命名空间(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos配置服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${spring.cloud.nacos.discovery.server-addr}
# 配置文件
config:
# 配置文件导入
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
file:
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
server:
# 服务端口
port: 9898
spring:
application:
# 应用名称,取pom文件中的artifactId
name: @artifactId@
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: @nacos.username@
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: @nacos.password@
# nacos注册中心
discovery:
# 命名空间id(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: nacos3.test.glsx.com:8848
# 启用监控功能
watch:
enabled: true
# 设置监控间隔为1000毫秒(即1秒)
watch-delay: 1000
config:
# 命名空间(必须使用命名空间id)
# namespace: b4196e36-e204-4e07-8612-f51b17401d6e
# 分组
group: DEFAULT_GROUP
# nacos配置服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${spring.cloud.nacos.discovery.server-addr}
# 配置文件
config:
# 配置文件导入
import:
- optional:nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
file:
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
spring:
profiles:
# 环境标识:dev、test、prod、release
active: dev
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="false">
<property name="log.path" value="/data/java_log/jetty/${artifactId}"/>
<property name="LOG_LEVEL" value="${logging.level:-INFO}" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%t]){faint} %clr([%X{traceId}]){red} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [${project.artifactId}] [%X{traceId}] [%thread] %-5level [%logger{36}.%method %line] - %msg%n"/>
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" class="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
class="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
class="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<!-- Console log output -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 错误日志 -->
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!-- 普通日志 -->
<appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/${artifactId}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/${artifactId}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- nacos 心跳 INFO 屏蔽 -->
<logger name="com.alibaba.nacos" level="OFF">
<appender-ref ref="error"/>
</logger>
<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter" level="DEBUG"/>
<root level="${LOG_LEVEL}">
<appender-ref ref="console"/>
<appender-ref ref="info"/>
<appender-ref ref="error"/>
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
server:
port: 9898
spring:
data:
redis:
host: 192.168.3.226
port: 6379
# 用户名密码如果没有配置,配置项注释掉
# username:
# password:
database: 0
timeout: 30000
connectTimeout: 30000
cloud:
gateway:
sign:
# 验签密钥对配置
kay-pairs:
# 前端业务模块:秘钥
dj_zhixin: "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b"
client2: "b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8"
# 排除路径(不需要验签的路径)
excluded-path:
- "/swagger-ui/index.html"
# 包含路径(不需要验签的路径)
excludedContainPath:
- "/v3/api-docs"
# 正则匹配(不需要验签的路径)
excludedRegexPath:
- "/v3/api-docs"
# 请求超时时间(毫秒),默认5分钟
request-timeout: 300000 # 5 * 60 * 1000
# 全局跨域配置
globalcors:
cors-configurations:
'[/**]':
allowed-origins: "*"
allowed-methods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
allowed-headers: "*"
# 设置为 true 时,allowed-origins 不能设置为 "*",需要指定具体的域名
allow-credentials: false
max-age: 3600
server:
webflux:
routes:
- id: gsc-upms-facade
uri: lb://gsc-upms-facade
predicates:
- Path=/facade/**
filters:
# 限流配置
- name: RequestRateLimiter
args:
key-resolver: '#{@remoteAddrKeyResolver}'
redis-rate-limiter.replenishRate: 100
redis-rate-limiter.burstCapacity: 200
#UPMS 模块
- id: gsc-upms-biz
uri: lb://gsc-upms-biz
predicates:
- Path=/admin/**
filters:
# 限流配置
- name: RequestRateLimiter
args:
key-resolver: '#{@remoteAddrKeyResolver}'
redis-rate-limiter.replenishRate: 100
redis-rate-limiter.burstCapacity: 200
# 固定路由转发配置 无修改
- id: openapi
uri: lb://gsc-gateway
predicates:
- Path=/v3/api-docs/**
filters:
- RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/$\{path}/v3/api-docs
swagger:
enabled: true
title: gsc Swagger API
gateway: http://${GATEWAY-HOST:127.0.0.1}:${GATEWAY-PORT:9999}
token-url: ${swagger.gateway}/auth/oauth2/token
scope: server
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!