Commit 8798b9bd by 叶立庆

初始化项目

0 parents
Showing 27 changed files with 1513 additions and 0 deletions
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
<?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>
<relativePath/>
</parent>
<groupId>com.gsc4cloud</groupId>
<artifactId>gsc-agent-manage-facade</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>gsc-agent-manage-facade</name>
<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 调用-->
<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>
<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>
/*
*
* 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.agentmanage;
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-agent-manage-facade")
@EnableGscFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class GscMain {
public static void main(String[] args) {
SpringApplication.run(GscMain.class, args);
}
}
package com.gsc4cloud.agentmanage.anotation;
import java.lang.annotation.*;
/**
* 需要兼容ropsession的地方添加此注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RopSession {
}
package com.gsc4cloud.agentmanage.config;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @Description todo
* @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.agentmanage.config;
import com.gsc4cloud.agentmanage.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 todo
* @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")*/; // 排除不需要拦截的路径
}
}
/*
*
* 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.agentmanage.controller;
import com.gsc4cloud.gsc.common.core.util.R;
import com.gsc4cloud.gsc.common.feign.annotation.NoToken;
import com.gsc4cloud.agentmanage.utils.ThreadLocalCache;
import com.gsc4cloud.agentmanage.request.sys.DetailRequest;
import com.gsc4cloud.agentmanage.response.rop.LoginAccountResponse;
import com.gsc4cloud.agentmanage.anotation.RopSession;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
/**
* 字典表前端控制器
*
* @author lengleng
* @date 2025/05/30
* @since 2019-03-19
*/
@RestController
@AllArgsConstructor
@RequestMapping("/dict")
@Tag(description = "dict", name = "字典管理模块")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysDictController {
/**
* 通过ID查询字典信息
*
* @param id 字典ID
* @return 包含字典信息的响应对象
*/
@PostMapping("/details/byId")
@Operation(summary = "通过ID查询字典信息")
public R getById(DetailRequest detailRequest) {
System.out.println("用户信息:" + ThreadLocalCache.getLoginInfo());
return R.ok("ok");
}
@RopSession // ROPsession注解,必须要rop登录信息
@PostMapping("/details/user")
@Operation(summary = "用户信息")
public R<LoginAccountResponse> getUser(DetailRequest detailRequest) {
System.out.println("用户信息:" + ThreadLocalCache.getLoginAccountInfo());
return R.ok(ThreadLocalCache.getLoginAccountInfo());
}
@GetMapping("/sign/test")
@Operation(summary = "验签测试")
public R<String> signTest(DetailRequest detailRequest) {
return R.ok("验签成功");
}
}
package com.gsc4cloud.agentmanage.interceptor;
import com.gsc4cloud.agentmanage.anotation.RopSession;
import com.gsc4cloud.agentmanage.manager.RopManager;
import com.gsc4cloud.agentmanage.utils.ThreadLocalCache;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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 todo
* @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.agentmanage.manager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gsc4cloud.agentmanage.config.RopApiConfig;
import com.gsc4cloud.agentmanage.utils.GLRopApiUtils;
import com.gsc4cloud.agentmanage.utils.ThreadLocalCache;
import com.gsc4cloud.agentmanage.response.rop.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @Description todo
* @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.agentmanage.request.sys;
import lombok.Data;
/**
* @Description todo
* @Author yelq
* @Date 2025/7/28-16:18
* @Version 1.0
*/
@Data
public class DetailRequest {
private Long id;
}
package com.gsc4cloud.agentmanage.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;
//notes = "手机号")
private String phone;
}
package com.gsc4cloud.agentmanage.response.rop;
import lombok.Data;
import lombok.ToString;
import java.util.List;
/**
* @Description todo
* @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.agentmanage.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.agentmanage.response.rop;
import lombok.Data;
/**
* @Description todo
* @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.agentmanage.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.agentmanage.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.agentmanage.utils;
import com.gsc4cloud.agentmanage.response.rop.LoginAccountResponse;
import com.gsc4cloud.agentmanage.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: gsc-agent-manage-facade
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: nacos
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: nacos
# 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:
- nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
server:
# 服务端口
port: 4008
spring:
application:
# 应用名称,取pom文件中的artifactId
name: gsc-agent-manage-facade
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: nacos
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: nacos
# 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:
- nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
path: /data/java_log/jetty/${spring.application.name}
level:
root: debug
server:
# 服务端口
port: 4008
spring:
application:
# 应用名称,取pom文件中的artifactId
name: gsc-agent-manage-facade
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: nacos
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: nacos
# 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:
- nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
server:
# 服务端口
port: 4008
spring:
application:
# 应用名称,取pom文件中的artifactId
name: gsc-agent-manage-facade
cloud:
nacos:
# nacos用户名,取pom文件中的nacos.username(父级的com.gsc4cloud:gsc下有默认定义)
username: nacos
# nacos密码,取pom文件中的nacos.password(父级的com.gsc4cloud:gsc下有默认定义)
password: nacos
# 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:
- nacos:${spring.application.name}-${spring.profiles.active}.yml
# 日志配置
logging:
config: classpath:logback-spring.xml
path: /data/java_log/jetty/${spring.application.name}
level:
root: info
spring:
profiles:
# 环境标识:dev、test、beta、release
active: dev
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
<?xml version="1.0" encoding="UTF-8"?>
<!--
小技巧: 在根pom里面设置统一存放路径,统一管理方便维护
<properties>
<log-path>/Users/lengleng</log-path>
</properties>
1. 其他模块加日志输出,直接copy本文件放在resources 目录即可
2. 注意修改 <property name="${log-path}/log.path" value=""/> 的value模块
-->
<configuration debug="false" scan="false">
<property name="log.path" value="/data/java_log/jetty/gsc-agent-manage-facade"/>
<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}}"/>
<!-- 文件日志格式 - 加入traceId -->
<property name="FILE_LOG_PATTERN" value=":%d{yyyy-MM-dd HH:mm:ss.SSS} %5p %t [%X{traceId}] %c{1}: %m%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>
<!-- Log file error output -->
<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>
</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}/gsc-agent-manage-facade.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${log.path}/%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<maxHistory>15</maxHistory>
<maxFileSize>50MB</maxFileSize>
</rollingPolicy>
<encoder>
<!-- 修改pattern,加入traceId -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}] [gsc-agent-manage-facade] [%thread] %-5level [%logger{36}.%method %line] - %msg%n</pattern>
</encoder>
<!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<!-- <MaxFileSize>50MB</MaxFileSize>-->
<!-- </triggeringPolicy>-->
</appender>
<!-- 新增:专门输出trace日志的appender(可选) -->
<appender name="trace" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/trace.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${log.path}/trace.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} | %X{traceId} | %thread | %-5level | %logger{50} | %msg%n</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"/>
<!-- 可选:为特定包设置trace级别日志 -->
<logger name="com.gsc4cloud.gsc" level="DEBUG" additivity="false">
<appender-ref ref="trace"/>
<appender-ref ref="console"/>
</logger>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="${LOG_LEVEL}">
<appender-ref ref="console"/>
<appender-ref ref="info"/>
<appender-ref ref="error"/>
</root>
</configuration>
\ No newline at end of file
# 广联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: gsc-agent-manage-facade-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-SNAPSHOT</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
package com.gsc4cloud.agentmanage.service;
import com.gsc4cloud.agentmanage.GscMain;
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 = GscMain.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!