Commit 148415df by 林冲

初始化项目

0 parents
Showing 36 changed files with 2075 additions and 0 deletions
FROM registry.cn-hangzhou.aliyuncs.com/dockerhub_mirror/java:21-anolis
WORKDIR /gps-upms-biz
ARG JAR_FILE=target/gsc-upms-biz.jar
COPY ${JAR_FILE} app.jar
EXPOSE 4000
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-vcp-thirdparty-facade</artifactId>
<packaging>jar</packaging>
<description>gsc 二手车第三方对接模块</description>
<dependencies>
<!-- pom.xml 中添加 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>
<!--二手车feign、entity等-->
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-vcp-api</artifactId>
<version>1.0.1-SNAPSHOT</version>
</dependency>
<!--feign 调用-->
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-common-feign</artifactId>
</dependency>
<!--接口文档-->
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-common-swagger</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>
<!--xss 过滤-->
<dependency>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-common-xss</artifactId>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
<profiles>
<profile>
<id>boot</id>
</profile>
<profile>
<id>cloud</id>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
<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>
</profile>
</profiles>
<build>
<!-- 打包不执行测试用例 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/*.xlsx</exclude>
<exclude>**/*.xls</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xlsx</include>
<include>**/*.xls</include>
</includes>
</resource>
</resources>
</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);
}
```
\ No newline at end of file
/*
*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the gsc4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*
*/
package com.gsc4cloud.gsc.facade.vpcthirdparty;
import com.gsc4cloud.gsc.common.feign.annotation.EnableGscFeignClients;
import com.gsc4cloud.gsc.common.swagger.annotation.EnableGscDoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 用户统一管理系统
*
* @author
* @date 2025/05/30
*/
@EnableGscDoc(value = "gsc-vcp-thirdparty-facade")
@EnableGscFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class VpcThirdpartyFacadeMain {
public static void main(String[] args) {
SpringApplication.run(VpcThirdpartyFacadeMain.class, args);
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.anotation;
import java.lang.annotation.*;
/**
* 需要兼容ropsession的地方添加此注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RopSession {
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.config;
import com.gsc4cloud.gsc.facade.vpcthirdparty.interceptor.OpenFeignInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Bean
public OpenFeignInterceptor openFeignInterceptor() {
return new OpenFeignInterceptor();
}
}
\ No newline at end of file
package com.gsc4cloud.gsc.facade.vpcthirdparty.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
/**
* @Description 日志打印配置
* @Author yelq
* @Date 2025/9/25-18:44
* @Version 1.0
*/
@Configuration
public class FilterConfig {
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(300); // 设置最大打印body长度
filter.setIncludeHeaders(true);
filter.setAfterMessagePrefix("请求信息: ");
return filter;
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.config;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @Description ROP api配置
* @Author yelq
* @Date 2025/7/28-19:09
* @Version 1.0
*/
@ToString
@Data
@Configuration
@ConfigurationProperties(prefix = "rop.api")
public class RopApiConfig {
private String appKey;
private String secret;
private String url;
private String contextPath;
private String method;
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.config;
import com.gsc4cloud.gsc.facade.vpcthirdparty.interceptor.SessionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Description web session拦截器配置
* @Author yelq
* @Date 2025/7/28-15:37
* @Version 1.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private SessionInterceptor sessionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(sessionInterceptor)
.addPathPatterns("/**") // 拦截所有路径
/*.excludePathPatterns("/login", "/error")*/; // 排除不需要拦截的路径
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/test")
public String test() {
return "test";
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.controller.auction;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.facade.vpcthirdparty.service.auction.CarAuctionService;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.CarAuctionRequest;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 车辆拍卖管理
*/
@RequestMapping("/auction")
@RestController
public class CarAuctionPushController {
@Autowired
private CarAuctionService carAuctionService;
/**
* 如果存在拍卖记录则更新状态,否则创建拍卖记录
* @param request 拍卖推送请求
* @return 是否处理成功
*/
@Operation(summary = "车辆的拍卖进展状态")
@PostMapping("/push")
public R pushAuction(@RequestBody @Valid CarAuctionRequest request) {
return carAuctionService.pushAuction(request);
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.controller.auction;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.facade.vpcthirdparty.service.auction.DeliveryOrderService;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.DeliveryOrderPayFinishRequest;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.DeliveryOrderRequest;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 交付工单管理
*/
@RequestMapping("/deliveryOrder")
@RestController
public class DeliveryOrderPushController {
@Autowired
private DeliveryOrderService deliveryOrderService;
@Operation(summary = "推送交付工单")
@PostMapping("/push")
public R push(@RequestBody @Valid DeliveryOrderRequest request) {
return deliveryOrderService.push(request);
}
@Operation(summary = "交付单付款完成")
@PostMapping("/payFinish")
public R payFinish(@RequestBody @Valid DeliveryOrderPayFinishRequest request) {
return deliveryOrderService.payFinish(request);
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.controller.esign;
import com.gsc4cloud.gsc.facade.vpcthirdparty.service.esign.SafeVerify;
import com.gsc4cloud.gsc.vpc.api.feign.thirdparty.esign.ESignRemote;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Map;
@RefreshScope
@Tag(name = "E签宝回调接口")
@RequestMapping(value = "/api/public/esign")
@RestController
public class ESignNotifyController extends HttpServlet {
@Value("${esign.appKey}")
private String appSecret;
@Autowired
private ESignRemote esignRemote;
private static final Logger log = LoggerFactory.getLogger(ESignNotifyController.class);
@PostMapping("/notify")
public Map<String, String> esignNotify(@RequestBody String param, HttpServletRequest request) throws IOException {
log.info("eSignNotify param:{}", param);
if (StringUtils.isBlank(param)) {
return Map.of("code", "500", "msg", "fail");
}
SafeVerify sv = new SafeVerify();
String res =sv.checkPass(param, request, appSecret);
if (!res.equals("true")) {
return Map.of("code", "500", "msg", "fail");
}
esignRemote.notify(param);
return Map.of("code", "200", "msg", "success");
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.handler;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.vpc.api.enums.ErrorCodeEnum;
import com.gsc4cloud.gsc.vpc.api.exception.BusinessException;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @Description 本地全局异常处理
* @Author yelq
* @Date 2025/9/19-20:47
* @Version 1.0
*/
@Order(9999)
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
public GlobalExceptionHandler() {
}
/**
* 处理业务异常
*/
@ExceptionHandler(BusinessException.class)
public ResponseEntity<R<?>> handleBusinessException(BusinessException e) {
log.error("业务异常: code={}, message={}", e.getCode(), e.getMessage(), e);
return ResponseEntity
.status(HttpStatus.OK)
.body(R.restResult(null, e.getCode(), e.getMessage()));
}
/**
* 参数校验异常统一处理
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public ResponseEntity<R<?>> handleValidationException(Exception e) {
BindingResult bindingResult = null;
if (e instanceof MethodArgumentNotValidException) {
bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
} else if (e instanceof BindException) {
bindingResult = ((BindException) e).getBindingResult();
}
String message = Optional.ofNullable(bindingResult)
.map(result -> result.getAllErrors().stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.joining("; ")))
.orElse("参数校验失败");
log.error("参数校验异常: {}", message, e);
return ResponseEntity
.status(HttpStatus.OK)
.body(R.restResult(null, ErrorCodeEnum.PARAM_INVALID.getCode(), message));
}
/**
* 处理请求方法不支持异常
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<R<?>> handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
log.error("请求方法不支持: {}", e.getMessage(), e);
return ResponseEntity
.status(HttpStatus.METHOD_NOT_ALLOWED)
.body(R.restResult(null,405, "请求方法不支持"));
}
/**
* 处理媒体类型不支持异常
*/
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity<R<?>> handleHttpMediaTypeNotSupportedException(
HttpMediaTypeNotSupportedException e) {
log.error("媒体类型不支持: {}", e.getMessage(), e);
return ResponseEntity
.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
.body(R.restResult(null,415, "媒体类型不支持"));
}
/**
* 处理空指针异常
*/
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<R<?>> handleNullPointerException(NullPointerException e) {
log.error("空指针异常", e);
return ResponseEntity
.status(HttpStatus.OK)
.body(R.restResult(null, ErrorCodeEnum.SYSTEM_ERROR.getCode(), ErrorCodeEnum.SYSTEM_ERROR.getMessage()));
}
/**
* 处理其他所有异常
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<R<?>> handleException(Exception e) {
log.error("系统异常", e);
return ResponseEntity
.status(HttpStatus.OK)
.body(R.restResult(null, ErrorCodeEnum.SYSTEM_ERROR.getCode(), ErrorCodeEnum.SYSTEM_ERROR.getMessage()));
}
/**
* 处理Feign客户端异常
*/
@ExceptionHandler(FeignException.class)
public ResponseEntity<R<?>> handleFeignException(FeignException e) {
log.error("Feign客户端异常: status={}, message={}", e.status(), e.getMessage(), e);
return ResponseEntity
.status(HttpStatus.OK)
.body(R.restResult(null, ErrorCodeEnum.FEIGN_ERROR.getCode(),"服务调用失败: " + e.getMessage()));
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Target;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import java.util.Objects;
@Slf4j
public class OpenFeignInterceptor implements RequestInterceptor {
@Resource
private Environment environment;
private static final String LOCAL_DEBUG = "localDebug";
@Override
public void apply(RequestTemplate requestTemplate) {
try {
// 传递上下文信息
// UserContextDTO userInfo = UserContext.getContext();
// if (isInValidUser(userInfo)) {
// userInfo = new UserContextDTO();
// userInfo.setId(SystemDefault.SYSTEM_USER_ID);
// userInfo.setAccountName(SystemDefault.SYSTEM_USER_ACCOUNT);
// userInfo.setRealName(SystemDefault.SYSTEM_REAL_NAME);
// }
// String baseCodeUser = Base64.getEncoder().encodeToString(JSONObject.toJSONString(userInfo).getBytes());
// requestTemplate.header(SystemDefault.REQUEST_ID, MDC.get(SystemDefault.TRACE_ID));
// requestTemplate.header(SystemDefault.SYSTEM_USER_INFO, baseCodeUser);
// 拦截Feign请求url
String enableLocalhost = environment.getProperty(LOCAL_DEBUG);
if (Objects.isNull(enableLocalhost)) {
return;
}
Target<?> target = requestTemplate.feignTarget();
String targetName = target.name();
String targetUrl = target.url();
String newUrl = targetUrl.replace(targetName, targetName + "-" + enableLocalhost);
requestTemplate.target(newUrl);
} catch (Exception exception) {
log.error("requestTemplate.header error: ", exception);
}
}
// private boolean isInValidUser(UserContextDTO userInfo) {
// return userInfo == null || StringUtils.isEmpty(userInfo.getAccountName()) || userInfo.getId() == null;
// }
}
\ No newline at end of file
package com.gsc4cloud.gsc.facade.vpcthirdparty.interceptor;
import com.gsc4cloud.gsc.facade.vpcthirdparty.anotation.RopSession;
import com.gsc4cloud.gsc.facade.vpcthirdparty.manager.RopManager;
import com.gsc4cloud.gsc.facade.vpcthirdparty.utils.ThreadLocalCache;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.reflect.Method;
/**
* @Description web session拦截器,用于验证ROP API调用时是否携带了有效会话ID
* @Author yelq
* @Date 2025/7/28-15:35
* @Version 1.0
*/
@Slf4j
@Component
public class SessionInterceptor implements HandlerInterceptor {
@Autowired
private RopManager ropManager;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
// 忽略swagger
if (path.startsWith("/swagger-ui") || path.contains("/v3/api-docs") || path.startsWith("/doc.html")) {
return true;
}
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
// 1. 检查方法上是否有特定注解
if (!method.isAnnotationPresent(RopSession.class)) {
// 没有RopSession,则跳过token验证
return true;
}
// 从请求参数中获取sessionId
String sessionId = request.getParameter("sessionId");
if (sessionId == null || sessionId.isEmpty()) {
// 如果没有sessionId参数,直接放行(或者可以根据需求返回错误)
throw new Exception("sessionId参数缺失");
}
ropManager.saveLoginInfo(sessionId);
// 无论是否找到用户信息,都继续执行后续流程
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 请求结束后清除ThreadLocal中的用户信息,防止内存泄漏
try {
ThreadLocalCache.removeLoginInfo();
ThreadLocalCache.removeLoginAccountInfo();
log.info("ThreadLocal用户信息已清除");
} catch (Exception e) {
log.warn("清除ThreadLocal用户信息时发生异常", e);
}
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.manager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gsc4cloud.gsc.facade.vpcthirdparty.config.RopApiConfig;
import com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop.*;
import com.gsc4cloud.gsc.facade.vpcthirdparty.utils.GLRopApiUtils;
import com.gsc4cloud.gsc.facade.vpcthirdparty.utils.ThreadLocalCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @Description ROP API调用管理类
* @Author yelq
* @Date 2025/7/28-19:24
* @Version 1.0
*/
@Component
public class RopManager {
@Autowired
private RopApiConfig ropApiConfig;
public void saveLoginInfo(String sessionId) throws Exception {
if (ropApiConfig.getContextPath() == null || ropApiConfig.getContextPath().isEmpty())
throw new Exception("缺少必要的rop配置");
if ("rop-dj-car-boutique".equals(ropApiConfig.getContextPath())){
ropDjCarBoutiqueHandler(sessionId);
return;
}
if ("rop-dj-smartcarlife".equals(ropApiConfig.getContextPath())){
ropDjSmartCarLifeHandler(sessionId);
return;
}
}
private void ropDjSmartCarLifeHandler(String sessionId) throws Exception {
//请求地址,区分环境
String url = ropApiConfig.getUrl();
String appKey = ropApiConfig.getAppKey();
String secret = ropApiConfig.getSecret();
//项目名称
String contextPath = ropApiConfig.getContextPath();
// 默认拼装路径
url = url.concat(contextPath).concat("/router");
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(4);
// 版本号,必填,默认1.0.0
params.add("v", "1.0.0");
// 接口名称,必填
params.add("method", ropApiConfig.getMethod());
// 参数,根据接口添加
params.add("sessionId", sessionId);
// post请求
RopResponse<Object> post = GLRopApiUtils.post(url, params, RopResponse.class, appKey, secret);
if (post.getData() != null) {
String data = JSON.toJSONString(post.getData());
// json字符串转换对象
UserInfoResponse loginObj = JSONObject.parseObject(data, UserInfoResponse.class);
if (loginObj != null && loginObj.getLoginAccount() != null ) {
LoginAccountResponse loginUserInfo = loginObj.getLoginAccount();
// 存储到当前线程
ThreadLocalCache.setLoginAccountInfo(loginUserInfo);
}
} else {
throw new Exception("用户信息获取失败: " + post.getMessage());
}
}
private void ropDjCarBoutiqueHandler(String sessionId) throws Exception {
//请求地址,区分环境
String url = ropApiConfig.getUrl();
String appKey = ropApiConfig.getAppKey();
String secret = ropApiConfig.getSecret();
//项目名称
String contextPath = ropApiConfig.getContextPath();
// 默认拼装路径
url = url.concat(contextPath).concat("/router");
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(4);
// 版本号,必填,默认1.0.0
params.add("v", "1.0.0");
// 接口名称,必填
params.add("method", ropApiConfig.getMethod());
// 参数,根据接口添加
params.add("sessionId", sessionId);
// post请求
RopResponse<Object> post = GLRopApiUtils.post(url, params, RopResponse.class, appKey, secret);
if (post.getData() != null) {
String data = JSON.toJSONString(post.getData());
// json字符串转换对象
LoginObjResponse loginObj = JSONObject.parseObject(data, LoginObjResponse.class);
if (loginObj != null && loginObj.getLoginUserInfoList() != null && !loginObj.getLoginUserInfoList().isEmpty()) {
LoginUserInfoResponse loginUserInfo = loginObj.getLoginUserInfoList().get(0);
// 存储到当前线程
ThreadLocalCache.setLoginInfo(loginUserInfo);
}
} else {
throw new Exception("用户信息获取失败: " + post.getMessage());
}
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop;
import lombok.Data;
import lombok.ToString;
import java.util.List;
@Data
@ToString
public class LoginAccountResponse {
// (notes = "登录类型2.员工 1.商户")
private Integer userType;
// (notes = "用户名")
private String loginAccout;
// (notes = "姓名")
private String userName;
// (notes = "商户名称")
private String merchantName;
// (notes = "商户账号层级")
private Integer accountLevel;
// (notes = "商户账号状态")
private Integer status;
// (notes = "商户号")
private Integer merchantNo;
// (notes = "渠道类型")
private String channelType;
// (notes = "商户模式 1.集团版 2.门店版")
private Integer merchantModel;
// (notes = "账号唯一id")
private String uuid;
// (notes = "头像")
private String staffAvatar;
// (notes = "是否超管(1:是否,0:否)")
private Integer isAdmin;
private String createdTime;
private List<String> merchantAccountList;
// (notes = "登录角色 3-区域运营 4-广联销售")
private Integer loginRole;
// (notes = "广联数科下角色名称")
private String roleName;
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/**
* @Description rop 登录返回对象
* @Author yelq
* @Date 2025/7/28-16:28
* @Version 1.0
*/
@ToString
@Data
public class LoginObjResponse {
private String sessionId;
private String noSignInUuid;
private Boolean needSelectAccount;
private List<LoginUserInfoResponse> loginUserInfoList;
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop;
import lombok.Data;
import lombok.ToString;
import org.springframework.beans.BeanUtils;
import java.io.Serializable;
import java.util.List;
/**
* 禁止改动(确实需要改动的与周海宝确认两边同步修改)
* @Title: LoginUserInfoResponse.java
* @Description:
* @author zhoulm
* @date 2024年8月2日 17:42:37
*/
@Data
@ToString
public class LoginUserInfoResponse implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3576264570350286128L;
// name = "accountName", notes = "登录账号", dataType = "string", required = true, example = "")
private String accountName;
// name = "merchantId", notes = "商户号", dataType = "int", required = true, example = "")
private Integer merchantId;
// notes = "账号类型(4门店,3片区(市级经销商),2大区(省级经销商),1总部(工厂))", dataType = "int", required = true, example = "")
private Integer accountLevel;
// notes = "用户类型(1:商户,2员工)", dataType = "int", required = true, example = "")
private Integer userType;
// name = "phone", notes = "手机号", dataType = "string", required = true, example = "")
private String phone;
/** 员工姓名**/
// name = "name", notes = "员工姓名", dataType = "string", required = true, example = "")
private String name;
// name = "duty", notes = "职务", dataType = "string", required = true, example = "")
private String duty;
/** 商户名称**/
// name = "merchantName", notes = "商户名称", dataType = "string", required = true, example = "")
private String merchantName;
// name="channelType", notes = "渠道类型", dataType = "int", example = "")
private Integer channelType;
/**是否超级管理员**/
private Boolean isSuper;
// notes = "账号ID")
private String uuid;
// name="createdDate", notes = "创建时间", dataType = "Date", example = "")
private String createdDate;
/**
* 用户数据权限商户ID
*/
private List<Integer> permissionMerchantIds;
/** 子登录信息**/
private LoginUserInfoResponse subLoginUser;
private List<String> merchantAccountList;
/** 登录角色**/
// name="loginRole", notes = "登录角色 1-超管 2-商户管理员 3-区域督导 4-驻店人员 5-广联销售 6-飞行督导 7-技师", example = "")
private Integer loginRole;
// notes = "选择的4S店商户号")
private Integer shopMerchantId;
// notes = "选择的4S店商户名称")
private String shopMerchantName;
// notes = "选择的业务场景")
private Byte sceneType;
// notes = "在当前选择的4S下的登录角色 3-区域督导 4-驻店人员", example = "")
private Integer loginRoleOnSelectMerchant;
// notes = "业务id(员工或者商户)")
private Integer bussinessId;
public LoginUserInfoResponse clone(){
LoginUserInfoResponse r = new LoginUserInfoResponse();
BeanUtils.copyProperties(this, r);
return r;
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop;
import lombok.Data;
/**
* @Description ROP API通用返回对象
* @Author yelq
* @Date 2025/7/28-16:12
* @Version 1.0
*/
@Data
public class RopResponse<T> {
private String code;
private String errId;
private String message;
private T data;
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop;
import lombok.Data;
import java.io.Serializable;
/**
* @Title: UserInfoResponse.java
* @Description: 用户个人信息返回实体
* @author caiym
* @date 2020年11月11日 11:07
* @version V1.0.0
* @Company: didihu.com.cn
* @Copyright Copyright (c) 2020
*/
@Data
public class UserInfoResponse implements Serializable {
private static final long serialVersionUID = -4845569468798367039L;
// (notes = "登录信息")
private LoginAccountResponse loginAccount;
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.service.auction;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.vpc.api.feign.thirdparty.auction.CarAuctionRemote;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.CarAuctionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CarAuctionService {
@Autowired
private CarAuctionRemote carAuctionRemote;
public R pushAuction(CarAuctionRequest request) {
return carAuctionRemote.createOrUpdate(request);
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.service.auction;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.vpc.api.feign.thirdparty.auction.DeliveryOrderRemote;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.DeliveryOrderPayFinishRequest;
import com.gsc4cloud.gsc.vpc.api.req.thirdparty.auction.DeliveryOrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DeliveryOrderService {
@Autowired
private DeliveryOrderRemote deliveryOrderRemote;
public R push(DeliveryOrderRequest request) {
return deliveryOrderRemote.create(request);
}
public R payFinish(DeliveryOrderPayFinishRequest request) {
return deliveryOrderRemote.payFinish(request);
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.service.esign;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Base64.Encoder;
/***
*
* @Description: 摘要加密算法辅助类
* @Team: 公有云技术支持小组
* @Author: 天云小生
* @Date: 2018年01月14日
*/
public class DigestHelper {
/***
* 获取请求签名值
*
* @param data
* 加密前数据
* @param key
* 密钥
* @param algorithm
* HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
* @param encoding
* 编码格式
* @return HMAC加密后16进制字符串
* @throws Exception
*/
public static String getSignature(String data, String key, String algorithm, String encoding) {
Mac mac = null;
try {
mac = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(encoding), algorithm);
mac.init(secretKey);
mac.update(data.getBytes(encoding));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("获取Signature签名信息异常:" + e.getMessage());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println("获取Signature签名信息异常:" + e.getMessage());
return null;
} catch (InvalidKeyException e) {
e.printStackTrace();
System.out.println("获取Signature签名信息异常:" + e.getMessage());
return null;
}
return byte2hex(mac.doFinal());
}
/***
* 计算文件的Content-MD5
*
* @param filePath
* @return
*/
public static String getContentMD5(String filePath) {
Encoder encoder = Base64.getEncoder();
// 获取文件MD5的二进制数组(128位)
byte[] bytes = getFileMD5Bytes128(filePath);
// 对文件MD5的二进制数组进行base64编码(而不是对32位的16进制字符串进行编码)
return encoder.encodeToString(bytes);
}
/***
* 获取文件MD5-二进制数组(128位)
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] getFileMD5Bytes128(String filePath) {
FileInputStream fis = null;
byte[] md5Bytes = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md5.update(buffer, 0, length);
}
md5Bytes = md5.digest();
fis.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return md5Bytes;
}
/***
* 获取文件SHA256-十六进制字符串(原文SHA256摘要)
*
* @param filePath
* @return
* @throws IOException
*/
public static String getFileSHA256(String filePath) {
FileInputStream fis = null;
byte[] md5Bytes = null;
String hashSHA256 = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
MessageDigest md5 = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md5.update(buffer, 0, length);
}
md5Bytes = md5.digest();
fis.close();
hashSHA256 = byte2hex(md5Bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return hashSHA256;
}
/***
* 获取字符串的SHA256-十六进制字符串
*
* @param str
* @return
* @throws IOException
*/
public static String getStringSHA256(String str) {
byte[] md5Bytes = null;
try {
md5Bytes = str.getBytes("UTF-8");
// 拿到一个SHA256转换器
MessageDigest messageDigest;
messageDigest = MessageDigest.getInstance("SHA-256");
// 输入的字符串转换成字节数组
byte[] inputByteArray = str.getBytes();
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
md5Bytes = messageDigest.digest();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byte2hex(md5Bytes);
}
/***
* 将byte[]转成16进制字符串
*
* @param data
*
* @return 16进制字符串
*/
public static String byte2hex(byte[] data) {
StringBuilder hash = new StringBuilder();
String stmp;
for (int n = 0; data != null && n < data.length; n++) {
stmp = Integer.toHexString(data[n] & 0XFF);
if (stmp.length() == 1)
hash.append('0');
hash.append(stmp);
}
return hash.toString();
}
}
/**
*
*/
package com.gsc4cloud.gsc.facade.vpcthirdparty.service.esign;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
/**
* @author chen_xi
* 验证签名
*/
@Slf4j
public class SafeVerify {
public String checkPass(String body, HttpServletRequest request, String appSecret) throws UnsupportedEncodingException {
String signTure = request.getHeader("X-Tsign-Open-SIGNATURE");
//1. 获取时间戳的字节流
String timestamp = request.getHeader("X-Tsign-Open-TIMESTAMP");
// String content_type =request
//2. 获取query请求字符串
String requestQuery =getRequestQueryStr(request);
//3. 获取body的数据
// String body =getRequestBody(request,"UTF-8");
//4、按照规则进行加密
String signData = timestamp + requestQuery + body;
log.info("加密前的数据:{}", signData);
String mySignature= DigestHelper.getSignature(signData, appSecret,"HmacSHA256","UTF-8");
log.info("加密出来的签名值:{},header里面的签名值:{}", mySignature, signTure);
if(StringUtils.isNotBlank(signTure) && StringUtils.isNotBlank(mySignature) && mySignature.equals(signTure)) {
System.out.println("校验通过");
return "true";
}else {
System.out.println("校验失败");
return "false";
}
}
/**
* 获取请求body
* @param request
* @param encoding
* @return
*/
private String getRequestBody(HttpServletRequest request, String encoding) {
// 请求内容RequestBody
String reqBody = null;
int contentLength = request.getContentLength();
if (contentLength < 0) {
return null;
}
byte buffer[] = new byte[contentLength];
try {
for (int i = 0; i < contentLength;) {
ServletInputStream inputStream = request.getInputStream();
int readlen = inputStream.read(buffer, i, contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
reqBody = new String(buffer, encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return reqBody;
}
/**
* 获取query请求字符串
* @param request
* @return
*/
private String getRequestQueryStr(HttpServletRequest request) {
//对 Query 参数按照字典对 Key 进行排序后,按照value1+value2方法拼接
//转换一下数据类型并排序
List<String> req_List= new ArrayList();
Enumeration<String> reqEnu =request.getParameterNames();
while (reqEnu.hasMoreElements()){
req_List.add(reqEnu.nextElement());
}
Collections.sort(req_List);
String requestQuery = "";
for (String key : req_List) {
String value = request.getParameter(key);
requestQuery += value == null ? "" : value;
}
System.out.println("获取的query请求字符串是:------》》》"+requestQuery);
return requestQuery;
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;
/**
* @Description 请求广联接口的工具类
* @Author
* @Date 2025/7/1-16:54
* @Version 1.0
*/
public class GLRopApiUtils {
public static <T> T post(String url, MultiValueMap<String, String> paramsMap, Class<T> responseType, String appKey, String secret) throws Exception {
MultiValueMap<String, String> params = getSysParams(appKey);
params.putAll(paramsMap);
for (Map.Entry<String, String> entry : params.toSingleValueMap().entrySet()) {
if (entry.getValue() == null || entry.getValue().isEmpty()) {
params.remove(entry.getKey());
}
}
String sign = sign(params.toSingleValueMap(), secret);
params.add("sign", sign);
return new RestTemplate().postForObject(url, params, responseType);
}
protected static MultiValueMap<String, String> getSysParams(String appKey) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(16);
params.add("appKey", appKey);
params.add("format", "json");
params.add("locale", "zh_CN");
return params;
}
public static String sign(Map<String, String> paramValues, String secret) {
try {
StringBuilder sb = new StringBuilder();
List<String> paramNames = new ArrayList(paramValues.size());
paramNames.addAll(paramValues.keySet());
Iterator var5;
String paramName;
Collections.sort(paramNames);
sb.append(secret);
var5 = paramNames.iterator();
while (var5.hasNext()) {
paramName = (String) var5.next();
sb.append(paramName).append((String) paramValues.get(paramName));
}
sb.append(secret);
byte[] sha1Digest = getSHA1Digest(sb.toString());
return byte2hex(sha1Digest);
} catch (IOException var7) {
throw new RuntimeException(var7);
}
}
private static byte[] getSHA1Digest(String data) throws IOException {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
bytes = md.digest(data.getBytes("UTF-8"));
return bytes;
} catch (GeneralSecurityException var3) {
throw new IOException(var3);
}
}
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
String hex = Integer.toHexString(bytes[i] & 255);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
}
package com.gsc4cloud.gsc.facade.vpcthirdparty.utils;
import com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop.LoginAccountResponse;
import com.gsc4cloud.gsc.facade.vpcthirdparty.response.rop.LoginUserInfoResponse;
public class ThreadLocalCache {
// rop-dj-car-boutique
private static ThreadLocal<LoginUserInfoResponse> loginInfoCache = new ThreadLocal<LoginUserInfoResponse>();
// rop-dj-smartcarlife
private static ThreadLocal<LoginAccountResponse> LoginAccountInfoCache = new ThreadLocal<LoginAccountResponse>();
public static void setLoginAccountInfo(LoginAccountResponse loginAccountInfo) {
LoginAccountInfoCache.set(loginAccountInfo);
}
public static LoginAccountResponse getLoginAccountInfo() {
return LoginAccountInfoCache.get();
}
public static void removeLoginAccountInfo() {
LoginAccountInfoCache.remove();
}
public static void setLoginInfo(LoginUserInfoResponse loginInfo) {
loginInfoCache.set(loginInfo);
}
public static LoginUserInfoResponse getLoginInfo() {
return loginInfoCache.get();
}
public static void removeLoginInfo() {
loginInfoCache.remove();
}
}
server:
# 服务端口
port: 4008
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:
- 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: 4008
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: 799f5259-b913-4673-b40c-33f96ce4601b
# 分组
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: 799f5259-b913-4673-b40c-33f96ce4601b
# 分组
group: DEFAULT_GROUP
# nacos配置服务地址,配置文件中的NACOS_HOST和NACOS_PORT
server-addr: ${spring.cloud.nacos.discovery.server-addr}
# 配置文件
config:
# 配置文件导入
import:
- 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
#E签宝信息
esign:
appId: "7439081342"
appKey: "8c00d8e276fde3f055ee37d8f103f566"
host: "https://smlopenapi.esign.cn"
sealId: "fa5d5fd5-99cc-4082-89ac-f3822ca02517"
server:
# 服务端口
port: 4008
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:
- 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: 4008
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:
- 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、beta、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
server:
port: 4002
spring:
data:
redis:
host: 192.168.3.226
port: 6379
# 用户名密码如果没有配置,配置项注释掉
# username:
# password:
database: 0
timeout: 30000
connectTimeout: 30000
redisson:
config:
singleServerConfig:
idleConnectionTimeout: 10000
connectTimeout: 5000
timeout: 3000
database: 0
# swagger 配置
swagger:
enabled: true
title: ${spring.application.name} Swagger API
gateway: http://${GATEWAY-HOST:127.0.0.1}:${GATEWAY-PORT:9999}
token-url: ${swagger.gateway}/auth/oauth2/token
scope: server
# rop 配置
rop:
api:
appkey: 48e5e13229b82c1b4e6e8c96151f0637
secret: c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b
url: https://dj.dev.glsx.com.cn/
contextPath: rop-dj-smartcarlife
method: dj.api.user.info
package com.gsc4cloud.gsc.facade.vpcthirdparty.service;
import com.gsc4cloud.gsc.facade.vpcthirdparty.VpcThirdpartyFacadeMain;
import org.junit.jupiter.api.Test;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import java.util.concurrent.TimeUnit;
/**
* @author zhoulm
* @version V1.0
* @Title: BaseServiceTest.java
* @Description:
* @date 2018年1月6日 下午1:23:03
* @Company: Didihu.com.cn
* @Copyright Copyright (c) 2015
*/
@SpringBootTest(classes = VpcThirdpartyFacadeMain.class)
public class BaseServiceTest {
@Autowired
private Redisson redisson;
@Autowired
private Environment environment;
@Test
public void Test() throws Exception {
RBucket<String> weiruizhifu = redisson.getBucket("weiruizhifu");
weiruizhifu.set("test",5, TimeUnit.SECONDS);
System.out.println(weiruizhifu.get());
// while ( true){
// System.out.println(weiruizhifu.get());
// Thread.sleep(1000);
// }
// System.out.println("test");
// System.out.println(environment.getProperty());
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!