style(framework): 优化代码格式与注解配置
This commit is contained in:
+1
-1
@@ -29,7 +29,7 @@ import java.util.Date;
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class CsBaseCreateTimeTb extends CsObject {
|
||||
@Schema(name ="创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@Schema(name = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createTime;
|
||||
}
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ import java.util.Date;
|
||||
@Setter
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
public class CsBaseUpdateTimeTb extends CsObject {
|
||||
@Schema(name ="更新时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@Schema(name = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
private Date updateTime;
|
||||
}
|
||||
|
||||
+10
-10
@@ -35,21 +35,13 @@ public class CsBaseUserCreateTimeTb extends CsObject {
|
||||
|
||||
@CreatedBy
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建人", hidden = true)
|
||||
@Schema(name = "创建人", hidden = true)
|
||||
private String createBy;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@Schema(name = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
private Date createTime;
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Create {
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Update {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
ToStringBuilder builder = new ToStringBuilder(this);
|
||||
@@ -64,4 +56,12 @@ public class CsBaseUserCreateTimeTb extends CsObject {
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Create {
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Update {
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -38,19 +38,19 @@ import java.util.Date;
|
||||
public class CsBaseUserTimeLogicTb extends CsObject {
|
||||
@CreatedBy
|
||||
@TableField(value = "create_by", fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建人", hidden = true)
|
||||
@Schema(name = "创建人", hidden = true)
|
||||
private String createBy;
|
||||
@LastModifiedBy
|
||||
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
|
||||
@Schema(name ="更新人", hidden = true)
|
||||
@Schema(name = "更新人", hidden = true)
|
||||
private String updateBy;
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建时间", hidden = true)
|
||||
@Schema(name = "创建时间", hidden = true)
|
||||
private Date createTime;
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
@Schema(name ="更新时间", hidden = true)
|
||||
@Schema(name = "更新时间", hidden = true)
|
||||
private Date updateTime;
|
||||
@Schema(name ="数据有效性", hidden = true)
|
||||
@Schema(name = "数据有效性", hidden = true)
|
||||
@TableLogic
|
||||
@TableField("available")
|
||||
private Integer available;
|
||||
|
||||
+12
-12
@@ -36,30 +36,22 @@ public class CsBaseUserTimeTb extends CsObject {
|
||||
|
||||
@CreatedBy
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建人", hidden = true)
|
||||
@Schema(name = "创建人", hidden = true)
|
||||
private String createBy;
|
||||
|
||||
@LastModifiedBy
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
@Schema(name ="更新人", hidden = true)
|
||||
@Schema(name = "更新人", hidden = true)
|
||||
private String updateBy;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
@Schema(name ="创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@Schema(name = "创建时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
private Date createTime;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||
@Schema(name ="更新时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
@Schema(name = "更新时间: yyyy-MM-dd HH:mm:ss", hidden = true)
|
||||
private Date updateTime;
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Create {
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Update {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
ToStringBuilder builder = new ToStringBuilder(this);
|
||||
@@ -74,4 +66,12 @@ public class CsBaseUserTimeTb extends CsObject {
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Create {
|
||||
}
|
||||
|
||||
/* 分组校验 */
|
||||
public @interface Update {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ import java.io.Serializable;
|
||||
public class CsPageArgs<T> implements Serializable {
|
||||
@NotNull(message = "参数page不能为空")
|
||||
@Min(value = 1, message = "参数page最小值为1")
|
||||
@Schema(name ="页码", example = "1")
|
||||
@Schema(name = "页码", example = "1")
|
||||
private Integer page;
|
||||
@NotNull(message = "参数size不能为空")
|
||||
@Min(value = 1, message = "参数size最小值为1")
|
||||
@Schema(name ="每页数据量", example = "10")
|
||||
@Schema(name = "每页数据量", example = "10")
|
||||
private Integer size;
|
||||
private T args;
|
||||
}
|
||||
|
||||
+1
-5
@@ -23,11 +23,7 @@ import lombok.Getter;
|
||||
@AllArgsConstructor
|
||||
public enum FileTypeEnum {
|
||||
/* 文件类型 */
|
||||
IMAGE("image", "图片"),
|
||||
DOC("doc", "文档"),
|
||||
VOICE("voice", "音频"),
|
||||
VIDEO("video", "视频"),
|
||||
OTHER("other", "其他");
|
||||
IMAGE("image", "图片"), DOC("doc", "文档"), VOICE("voice", "音频"), VIDEO("video", "视频"), OTHER("other", "其他");
|
||||
|
||||
private final String code;
|
||||
private final String description;
|
||||
|
||||
+5
-5
@@ -33,11 +33,6 @@ import java.net.UnknownHostException;
|
||||
*/
|
||||
@Slf4j
|
||||
public class BootApplication {
|
||||
@Bean
|
||||
public CsSpringBeanHolder springBeanHolder() {
|
||||
return new CsSpringBeanHolder();
|
||||
}
|
||||
|
||||
protected static void inited(ConfigurableApplicationContext application) throws UnknownHostException {
|
||||
Environment env = application.getEnvironment();
|
||||
String ip = InetAddress.getLocalHost().getHostAddress();
|
||||
@@ -51,4 +46,9 @@ public class BootApplication {
|
||||
\tSwagger文档: \thttp://{}:{}{}/doc.html
|
||||
----------------------------------------------------------""", port, path, ip, port, path, ip, port, path);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CsSpringBeanHolder springBeanHolder() {
|
||||
return new CsSpringBeanHolder();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -29,6 +29,6 @@ import java.util.Objects;
|
||||
public class CsRequestHolder {
|
||||
|
||||
public static HttpServletRequest getHttpServletRequest() {
|
||||
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
|
||||
return ((ServletRequestAttributes)Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
|
||||
}
|
||||
}
|
||||
|
||||
+13
-15
@@ -32,8 +32,8 @@ import java.util.List;
|
||||
@SuppressWarnings({"unchecked", "all"})
|
||||
public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBean {
|
||||
|
||||
private static ApplicationContext applicationContext = null;
|
||||
private static final List<CallBack> CALL_BACKS = new ArrayList<>();
|
||||
private static ApplicationContext applicationContext = null;
|
||||
private static boolean addCallback = true;
|
||||
|
||||
/**
|
||||
@@ -55,7 +55,7 @@ public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBe
|
||||
*/
|
||||
public static <T> T getBean(String name) {
|
||||
assertContextInjected();
|
||||
return (T) applicationContext.getBean(name);
|
||||
return (T)applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,8 +110,7 @@ public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBe
|
||||
private static void assertContextInjected() {
|
||||
if (applicationContext == null) {
|
||||
throw new IllegalStateException(
|
||||
"applicaitonContext属性未注入, 请在applicationContext" +
|
||||
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
|
||||
"applicaitonContext属性未注入, 请在applicationContext" + ".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +122,15 @@ public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBe
|
||||
applicationContext = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 @Service 的所有 bean 名称
|
||||
*
|
||||
* @return /
|
||||
*/
|
||||
public static List<String> getAllServiceBeanName() {
|
||||
return new ArrayList<>(Arrays.asList(applicationContext.getBeanNamesForAnnotation(Service.class)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
CsSpringBeanHolder.clearHolder();
|
||||
@@ -131,8 +139,7 @@ public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBe
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
if (CsSpringBeanHolder.applicationContext != null) {
|
||||
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" +
|
||||
CsSpringBeanHolder.applicationContext);
|
||||
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + CsSpringBeanHolder.applicationContext);
|
||||
}
|
||||
CsSpringBeanHolder.applicationContext = applicationContext;
|
||||
if (addCallback) {
|
||||
@@ -144,15 +151,6 @@ public class CsSpringBeanHolder implements ApplicationContextAware, DisposableBe
|
||||
CsSpringBeanHolder.addCallback = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 @Service 的所有 bean 名称
|
||||
*
|
||||
* @return /
|
||||
*/
|
||||
public static List<String> getAllServiceBeanName() {
|
||||
return new ArrayList<>(Arrays.asList(applicationContext.getBeanNamesForAnnotation(Service.class)));
|
||||
}
|
||||
|
||||
interface CallBack {
|
||||
|
||||
/**
|
||||
|
||||
+1
@@ -27,6 +27,7 @@ import org.springframework.validation.ObjectError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/**
|
||||
* 全局异常处理
|
||||
*
|
||||
|
||||
+12
-24
@@ -27,61 +27,49 @@ public enum CsMpQTypeEnum {
|
||||
/**
|
||||
* 大于等于
|
||||
*/
|
||||
,
|
||||
GREATER_THAN
|
||||
, GREATER_THAN
|
||||
/**
|
||||
* 小于等于
|
||||
*/
|
||||
,
|
||||
LESS_THAN
|
||||
, LESS_THAN
|
||||
/**
|
||||
* 中模糊查询
|
||||
*/
|
||||
,
|
||||
INNER_LIKE
|
||||
, INNER_LIKE
|
||||
/**
|
||||
* 左模糊查询
|
||||
*/
|
||||
,
|
||||
LEFT_LIKE
|
||||
, LEFT_LIKE
|
||||
/**
|
||||
* 右模糊查询
|
||||
*/
|
||||
,
|
||||
RIGHT_LIKE
|
||||
, RIGHT_LIKE
|
||||
/**
|
||||
* 小于
|
||||
*/
|
||||
,
|
||||
LESS_THAN_NQ
|
||||
, LESS_THAN_NQ
|
||||
/**
|
||||
* 包含
|
||||
*/
|
||||
,
|
||||
IN
|
||||
, IN
|
||||
/**
|
||||
* 不包含
|
||||
*/
|
||||
,
|
||||
NOT_IN
|
||||
, NOT_IN
|
||||
/**
|
||||
* 不等于
|
||||
*/
|
||||
,
|
||||
NOT_EQUAL
|
||||
, NOT_EQUAL
|
||||
/**
|
||||
* between(注:被注解的属性一定得是数组或者集合, 长度大于等于2)
|
||||
*/
|
||||
,
|
||||
BETWEEN
|
||||
, BETWEEN
|
||||
/**
|
||||
* 不为空
|
||||
*/
|
||||
,
|
||||
NOT_NULL
|
||||
, NOT_NULL
|
||||
/**
|
||||
* 为空
|
||||
*/
|
||||
,
|
||||
IS_NULL
|
||||
, IS_NULL
|
||||
}
|
||||
|
||||
+2
-9
@@ -85,6 +85,7 @@ public enum DataTypeEnum {
|
||||
* impala
|
||||
*/
|
||||
IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'");
|
||||
private static final String JDBC_URL_PREFIX = "jdbc:";
|
||||
private String feature;
|
||||
private String desc;
|
||||
private String driver;
|
||||
@@ -92,16 +93,8 @@ public enum DataTypeEnum {
|
||||
private String keywordSuffix;
|
||||
private String aliasPrefix;
|
||||
private String aliasSuffix;
|
||||
private static final String JDBC_URL_PREFIX = "jdbc:";
|
||||
|
||||
DataTypeEnum(
|
||||
String feature,
|
||||
String desc,
|
||||
String driver,
|
||||
String keywordPrefix,
|
||||
String keywordSuffix,
|
||||
String aliasPrefix,
|
||||
String aliasSuffix) {
|
||||
DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) {
|
||||
this.feature = feature;
|
||||
this.desc = desc;
|
||||
this.driver = driver;
|
||||
|
||||
+2
-1
@@ -61,6 +61,7 @@ public class MpCustomP6SpyLogger implements MessageFormattingStrategy {
|
||||
sql = sql.replaceAll("\\s+", " ").trim();
|
||||
}
|
||||
// 格式化并加上颜色
|
||||
return String.format("CuteJava - %s%s%s %s[%s] %sREVIEW_SQL [Interval: %dms]%s -> %s;", RED, now, RESET, GREEN, Thread.currentThread().getName(), BLUE, elapsed, RESET, sql);
|
||||
return String.format("CuteJava - %s%s%s %s[%s] %sREVIEW_SQL [Interval: %dms]%s -> %s;", RED, now, RESET, GREEN, Thread.currentThread().getName(), BLUE,
|
||||
elapsed, RESET, sql);
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -62,10 +62,9 @@ public class RemoveDruidAdConfig {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest)request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse)response;
|
||||
if (httpRequest.getRequestURI().endsWith("js/common.js")) {
|
||||
// 获取common.js
|
||||
String text = Utils.readFromResource(filePath);
|
||||
|
||||
+1
-5
@@ -69,11 +69,7 @@ public class CsMpAnyQUtil {
|
||||
return baseMapper.selectPage(page, queryWrapper);
|
||||
}
|
||||
|
||||
public static <T, M> Page<M> selectPage(
|
||||
BaseMapper<T> baseMapper,
|
||||
Page<T> page,
|
||||
Object queryParams,
|
||||
Class<M> mapperClazz) {
|
||||
public static <T, M> Page<M> selectPage(BaseMapper<T> baseMapper, Page<T> page, Object queryParams, Class<M> mapperClazz) {
|
||||
QueryWrapper<T> queryWrapper = CsMpQUtil.build(queryParams);
|
||||
Page<T> tPage = baseMapper.selectPage(page, queryWrapper);
|
||||
Page<M> mapperTarget = new Page<>();
|
||||
|
||||
+69
-96
@@ -64,6 +64,69 @@ public class CsMpCmdGenUtil {
|
||||
private String parentPackageName = "cn.odboy";
|
||||
private String parentModuleName;
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getEntityConfigConsumer() {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.entityBuilder().enableLombok()
|
||||
// 如果不需要生成注解, 去掉.enableTableFieldAnnotation()
|
||||
.enableTableFieldAnnotation().enableFileOverride().naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel)
|
||||
.idType(IdType.AUTO);
|
||||
}
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer(List<String> tableNames) {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.enableCapitalMode().enableSkipView().disableSqlFilter().addInclude(tableNames)
|
||||
// 实体类生成策略
|
||||
.entityBuilder().superClass(CsBaseUserTimeTb.class).addIgnoreColumns("create_time", "update_time", "create_by", "update_by")
|
||||
// 开启生成实体时生成字段注解。
|
||||
// 会在实体类的属性前,添加[@TableField("nickname")]
|
||||
.enableTableFieldAnnotation().disableSerialVersionUID()
|
||||
// 阶段2:Mapper策略配置
|
||||
.mapperBuilder()
|
||||
// 开启 @Mapper 注解。
|
||||
// 会在mapper接口上添加注解[@Mapper]
|
||||
// .enableMapperAnnotation()
|
||||
// 启用 BaseResultMap 生成。
|
||||
// 会在mapper.xml文件生成[通用查询映射结果]配置。
|
||||
// .enableBaseResultMap()
|
||||
// 启用 BaseColumnList。
|
||||
// 会在mapper.xml文件生成[通用查询结果列 ]配置
|
||||
// .enableBaseColumnList()
|
||||
// 阶段4:Controller策略配置
|
||||
.controllerBuilder()
|
||||
// 会在控制类中加[@RestController]注解。
|
||||
.enableRestStyle()
|
||||
// 开启驼峰转连字符
|
||||
.enableHyphenStyle().build();
|
||||
}
|
||||
|
||||
private static Consumer<GlobalConfig.Builder> getGlobalConfigConsumer() {
|
||||
String outputDir = projectRootPath + "CodeGen";
|
||||
return globalConfigBuilder -> globalConfigBuilder.enableSwagger().outputDir(outputDir).author("codegen").commentDate("yyyy-MM-dd")
|
||||
.dateType(DateType.TIME_PACK);
|
||||
}
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer() {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.mapperBuilder().mapperAnnotation(Mapper.class).formatMapperFileName("%sMapper")
|
||||
.formatXmlFileName("%sMapper").entityBuilder().formatFileName("%sTb");
|
||||
}
|
||||
|
||||
private static Consumer<DataSourceConfig.Builder> getDataSourceConfigConsumer() {
|
||||
return builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
|
||||
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
|
||||
if (typeCode == Types.SMALLINT) {
|
||||
return DbColumnType.INTEGER;
|
||||
}
|
||||
if (typeCode == Types.DATE) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
if (typeCode == Types.TIME) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
if (typeCode == Types.TIMESTAMP) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
return typeRegistry.getColumnType(metaInfo);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 代码生成函数
|
||||
*
|
||||
@@ -75,8 +138,7 @@ public class CsMpCmdGenUtil {
|
||||
this.parentModuleName = moduleName;
|
||||
// 1.数据库配置
|
||||
DataSourceConfig.Builder dataSourceConfigBuilder =
|
||||
new DataSourceConfig.Builder(this.databaseUrl, this.databaseUsername, this.databasePassword).driverClassName(
|
||||
this.driverClassName);
|
||||
new DataSourceConfig.Builder(this.databaseUrl, this.databaseUsername, this.databasePassword).driverClassName(this.driverClassName);
|
||||
dataSourceConfigBuilder.dbQuery(DB_QUERY);
|
||||
dataSourceConfigBuilder.keyWordsHandler(new MySqlKeyWordsHandler());
|
||||
// 1.1.快速生成器
|
||||
@@ -116,13 +178,10 @@ public class CsMpCmdGenUtil {
|
||||
fastAutoGenerator.strategyConfig(getEntityConfigConsumer());
|
||||
// 5.2.Controller策略配置
|
||||
// 开启生成@RestController控制器
|
||||
fastAutoGenerator.strategyConfig(strategyConfigBuilder -> strategyConfigBuilder.controllerBuilder()
|
||||
.enableRestStyle());
|
||||
fastAutoGenerator.strategyConfig(strategyConfigBuilder -> strategyConfigBuilder.controllerBuilder().enableRestStyle());
|
||||
// 如果不需要生成Controller, fastAutoGenerator.templateConfig(templateConfig -> templateConfig.controller(""))。5.3.Service策略配置:格式化service接口和实现类的文件名称, 去掉默认的ServiceName前面的I
|
||||
fastAutoGenerator.strategyConfig(
|
||||
strategyConfigBuilder -> strategyConfigBuilder.serviceBuilder()
|
||||
.formatServiceFileName("%sService")
|
||||
.formatServiceImplFileName("%sServiceImpl"));
|
||||
strategyConfigBuilder -> strategyConfigBuilder.serviceBuilder().formatServiceFileName("%sService").formatServiceImplFileName("%sServiceImpl"));
|
||||
// 5.4.Mapper策略配置
|
||||
// 格式化 mapper文件名,格式化xml实现类文件名称
|
||||
fastAutoGenerator.strategyConfig(getStrategyConfigConsumer());
|
||||
@@ -130,99 +189,13 @@ public class CsMpCmdGenUtil {
|
||||
fastAutoGenerator.execute();
|
||||
}
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getEntityConfigConsumer() {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.entityBuilder()
|
||||
.enableLombok()
|
||||
// 如果不需要生成注解, 去掉.enableTableFieldAnnotation()
|
||||
.enableTableFieldAnnotation()
|
||||
.enableFileOverride()
|
||||
.naming(NamingStrategy.underline_to_camel)
|
||||
.columnNaming(NamingStrategy.underline_to_camel)
|
||||
.idType(IdType.AUTO);
|
||||
}
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer(List<String> tableNames) {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.enableCapitalMode()
|
||||
.enableSkipView()
|
||||
.disableSqlFilter()
|
||||
.addInclude(tableNames)
|
||||
// 实体类生成策略
|
||||
.entityBuilder()
|
||||
.superClass(CsBaseUserTimeTb.class)
|
||||
.addIgnoreColumns("create_time", "update_time", "create_by", "update_by")
|
||||
// 开启生成实体时生成字段注解。
|
||||
// 会在实体类的属性前,添加[@TableField("nickname")]
|
||||
.enableTableFieldAnnotation()
|
||||
.disableSerialVersionUID()
|
||||
// 阶段2:Mapper策略配置
|
||||
.mapperBuilder()
|
||||
// 开启 @Mapper 注解。
|
||||
// 会在mapper接口上添加注解[@Mapper]
|
||||
// .enableMapperAnnotation()
|
||||
// 启用 BaseResultMap 生成。
|
||||
// 会在mapper.xml文件生成[通用查询映射结果]配置。
|
||||
// .enableBaseResultMap()
|
||||
// 启用 BaseColumnList。
|
||||
// 会在mapper.xml文件生成[通用查询结果列 ]配置
|
||||
// .enableBaseColumnList()
|
||||
// 阶段4:Controller策略配置
|
||||
.controllerBuilder()
|
||||
// 会在控制类中加[@RestController]注解。
|
||||
.enableRestStyle()
|
||||
// 开启驼峰转连字符
|
||||
.enableHyphenStyle()
|
||||
.build();
|
||||
}
|
||||
|
||||
private Consumer<PackageConfig.Builder> getPackageConfigConsumer() {
|
||||
String mapperPath = projectRootPath + "CodeGen/resources/mapper";
|
||||
if (StrUtil.isBlank(this.parentModuleName)) {
|
||||
throw new BadRequestException("模块名称必填");
|
||||
}
|
||||
return packageConfigBuilder -> packageConfigBuilder.parent(this.parentPackageName)
|
||||
.moduleName(this.parentModuleName)
|
||||
.entity("dal.dataobject")
|
||||
.mapper("dal.mysql")
|
||||
.service("service")
|
||||
.serviceImpl("service.impl")
|
||||
.controller("controller")
|
||||
.pathInfo(Collections.singletonMap(OutputFile.xml, mapperPath));
|
||||
}
|
||||
|
||||
private static Consumer<GlobalConfig.Builder> getGlobalConfigConsumer() {
|
||||
String outputDir = projectRootPath + "CodeGen";
|
||||
return globalConfigBuilder -> globalConfigBuilder.enableSwagger()
|
||||
.outputDir(outputDir)
|
||||
.author("codegen")
|
||||
.commentDate("yyyy-MM-dd")
|
||||
.dateType(DateType.TIME_PACK);
|
||||
}
|
||||
|
||||
private static Consumer<StrategyConfig.Builder> getStrategyConfigConsumer() {
|
||||
return strategyConfigBuilder -> strategyConfigBuilder.mapperBuilder()
|
||||
.mapperAnnotation(Mapper.class)
|
||||
.formatMapperFileName("%sMapper")
|
||||
.formatXmlFileName("%sMapper")
|
||||
.entityBuilder()
|
||||
.formatFileName("%sTb");
|
||||
}
|
||||
|
||||
private static Consumer<DataSourceConfig.Builder> getDataSourceConfigConsumer() {
|
||||
return builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
|
||||
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
|
||||
if (typeCode == Types.SMALLINT) {
|
||||
return DbColumnType.INTEGER;
|
||||
}
|
||||
if (typeCode == Types.DATE) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
if (typeCode == Types.TIME) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
if (typeCode == Types.TIMESTAMP) {
|
||||
return DbColumnType.DATE;
|
||||
}
|
||||
return typeRegistry.getColumnType(metaInfo);
|
||||
});
|
||||
return packageConfigBuilder -> packageConfigBuilder.parent(this.parentPackageName).moduleName(this.parentModuleName).entity("dal.dataobject")
|
||||
.mapper("dal.mysql").service("service").serviceImpl("service.impl").controller("controller")
|
||||
.pathInfo(Collections.singletonMap(OutputFile.xml, mapperPath));
|
||||
}
|
||||
}
|
||||
+13
-13
@@ -163,19 +163,6 @@ public class CsMpQUtil {
|
||||
return fields;
|
||||
}
|
||||
|
||||
@TableName("test_domain")
|
||||
private static class TestDomain {
|
||||
@NotNull(groups = CsBaseUserTimeTb.Update.class)
|
||||
@TableId(value = "user_id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
@TableField(value = "dept_id")
|
||||
private Long deptId;
|
||||
@NotBlank
|
||||
private String username;
|
||||
@NotBlank
|
||||
private String nickName;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
QueryWrapper<TestDomain> query = new QueryWrapper<>();
|
||||
query.or(wrapper -> wrapper.eq("username", 1).or().eq("nickname", 2));
|
||||
@@ -192,4 +179,17 @@ public class CsMpQUtil {
|
||||
System.err.println("getTargetSql=================================");
|
||||
System.err.println(query.getTargetSql());
|
||||
}
|
||||
|
||||
@TableName("test_domain")
|
||||
private static class TestDomain {
|
||||
@NotNull(groups = CsBaseUserTimeTb.Update.class)
|
||||
@TableId(value = "user_id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
@TableField(value = "dept_id")
|
||||
private Long deptId;
|
||||
@NotBlank
|
||||
private String username;
|
||||
@NotBlank
|
||||
private String nickName;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-4
@@ -157,10 +157,7 @@ public interface CsMpMapper<E> extends BaseMapper<E> {
|
||||
* @param clazz 期望的对象类型
|
||||
* @return IPage<T>
|
||||
*/
|
||||
default <T> CsPageResult<T> queryFeatureClazzPage(
|
||||
Pageable pageable,
|
||||
LambdaQueryChainWrapper<E> wrapper,
|
||||
Class<T> clazz) {
|
||||
default <T> CsPageResult<T> queryFeatureClazzPage(Pageable pageable, LambdaQueryChainWrapper<E> wrapper, Class<T> clazz) {
|
||||
int pageNumber = pageable.getPageNumber();
|
||||
int pageSize = pageable.getPageSize();
|
||||
pageNumber = pageNumber <= 0 ? 1 : pageNumber;
|
||||
|
||||
+1
-4
@@ -59,10 +59,7 @@ public interface CsMpService<T> extends IService<T> {
|
||||
|
||||
CsPageResult<T> queryClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable);
|
||||
|
||||
<G> CsPageResult<G> queryFeatureClazzPageByArgs(
|
||||
LambdaQueryWrapper<T> wrapper,
|
||||
IPage<T> pageable,
|
||||
Class<G> targetClazz);
|
||||
<G> CsPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable, Class<G> targetClazz);
|
||||
|
||||
<G, Q> CsPageResult<G> queryFeatureClazzPageByArgs(Q criteria, IPage<T> pageable, Class<G> targetClazz);
|
||||
|
||||
|
||||
+1
-4
@@ -209,10 +209,7 @@ public class CsMpServiceImpl<M extends CsMpMapper<T>, T> extends ServiceImpl<M,
|
||||
* @param pageable 分页参数
|
||||
* @param targetClazz 目标类型
|
||||
*/
|
||||
public <G> CsPageResult<G> queryFeatureClazzPageByArgs(
|
||||
LambdaQueryWrapper<T> wrapper,
|
||||
IPage<T> pageable,
|
||||
Class<G> targetClazz) {
|
||||
public <G> CsPageResult<G> queryFeatureClazzPageByArgs(LambdaQueryWrapper<T> wrapper, IPage<T> pageable, Class<G> targetClazz) {
|
||||
if (wrapper == null) {
|
||||
wrapper = new LambdaQueryWrapper<>();
|
||||
}
|
||||
|
||||
+1
-2
@@ -33,8 +33,7 @@ public class QuartzRunnable implements Callable<Object> {
|
||||
private final Method method;
|
||||
private final String params;
|
||||
|
||||
public QuartzRunnable(String beanName, String methodName, String params)
|
||||
throws NoSuchMethodException, SecurityException {
|
||||
public QuartzRunnable(String beanName, String methodName, String params) throws NoSuchMethodException, SecurityException {
|
||||
this.target = CsSpringBeanHolder.getBean(beanName);
|
||||
this.params = params;
|
||||
if (StringUtils.isNotBlank(params)) {
|
||||
|
||||
+2
-4
@@ -31,7 +31,6 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@SuppressWarnings({"unchecked", "all"})
|
||||
@@ -205,9 +204,8 @@ public class CsRedisHelper {
|
||||
public void scanDel(String pattern) {
|
||||
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
|
||||
try (Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection(
|
||||
(RedisCallback<Cursor<byte[]>>) connection -> (Cursor<byte[]>) new ConvertingCursor<>(
|
||||
connection.scan(options),
|
||||
redisTemplate.getKeySerializer()::deserialize))) {
|
||||
(RedisCallback<Cursor<byte[]>>)connection -> (Cursor<byte[]>)new ConvertingCursor<>(connection.scan(options),
|
||||
redisTemplate.getKeySerializer()::deserialize))) {
|
||||
while (cursor.hasNext()) {
|
||||
redisTemplate.delete(cursor.next());
|
||||
}
|
||||
|
||||
+1
-7
@@ -53,13 +53,7 @@ public class RedisConfiguration {
|
||||
* 自动识别json对象白名单配置(仅允许解析的包名, 范围越小越安全)<br/> 未配置可能导致, 登录失败, 反复登录等问题
|
||||
*/
|
||||
private static final String[] WHITELIST_STR =
|
||||
{
|
||||
"org.springframework",
|
||||
"cn.odboy.system.dal.dataobject",
|
||||
"cn.odboy.system.dal.model",
|
||||
"cn.odboy.task.dal.dataobject",
|
||||
"cn.odboy.task.dal.model",
|
||||
};
|
||||
{"org.springframework", "cn.odboy.system.dal.dataobject", "cn.odboy.system.dal.model", "cn.odboy.task.dal.dataobject", "cn.odboy.task.dal.model",};
|
||||
|
||||
/**
|
||||
* 设置 redis 数据默认过期时间,默认2小时 设置@cacheable 序列化方式
|
||||
|
||||
+2
-8
@@ -49,14 +49,8 @@ public class AsyncTheadPoolConfig implements AsyncConfigurer {
|
||||
// 自定义工厂
|
||||
ThreadFactory factory = r -> new Thread(r, "DefaultAsync-" + new AtomicInteger(1).getAndIncrement());
|
||||
// 自定义线程池
|
||||
return new ThreadPoolExecutor(
|
||||
asyncTaskPool.getCorePoolSize(),
|
||||
asyncTaskPool.getMaxPoolSize(),
|
||||
asyncTaskPool.getKeepAliveSeconds(),
|
||||
TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(asyncTaskPool.getQueueCapacity()),
|
||||
factory,
|
||||
new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
return new ThreadPoolExecutor(asyncTaskPool.getCorePoolSize(), asyncTaskPool.getMaxPoolSize(), asyncTaskPool.getKeepAliveSeconds(), TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(asyncTaskPool.getQueueCapacity()), factory, new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
-1
@@ -25,7 +25,6 @@ import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class DateStringArraysToListDateConverter implements Converter<String[], List<Date>> {
|
||||
|
||||
+6
-6
@@ -91,17 +91,17 @@ public class ConfigurerAdapter implements WebMvcConfigurer {
|
||||
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
// 开启引用检测, 枚举支持
|
||||
/// 是否输出值为null的字段
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue);
|
||||
/// 字段如果为null,输出为false,而非null
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullBooleanAsFalse);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullBooleanAsFalse);
|
||||
/// 字段如果为null,输出为[],而非null
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullListAsEmpty);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullListAsEmpty);
|
||||
/// 字符类型字段如果为null,输出为"",而非null
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullStringAsEmpty);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullStringAsEmpty);
|
||||
/// 太具体的数值会直接影响逻辑本身, 所以不要这个
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullNumberAsZero);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteNullNumberAsZero);
|
||||
/// 全局Long转字符串,会导致基础框架本身异常, 所以不要这个
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteLongAsString);
|
||||
// config.setWriterFeatures(JSONWriter.Feature.WriteLongAsString);
|
||||
config.setWriterFeatures(JSONWriter.Feature.WriteEnumUsingToString);
|
||||
config.setWriterFeatures(JSONWriter.Feature.ReferenceDetection);
|
||||
fastJsonConverter.setFastJsonConfig(config);
|
||||
|
||||
+1
@@ -19,6 +19,7 @@ package cn.odboy.framework.websocket.config;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
|
||||
|
||||
/**
|
||||
* 自动注册使用了 @ServerEndpoint 注解声明的 WebSocket 端点对象
|
||||
*
|
||||
|
||||
+6
-17
@@ -61,9 +61,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
* @param <U> /
|
||||
* @return /
|
||||
*/
|
||||
public static <T, U extends Comparable<? super U>> List<T> streamAscSort(
|
||||
List<T> data,
|
||||
Function<? super T, ? extends U> keyExtractor) {
|
||||
public static <T, U extends Comparable<? super U>> List<T> streamAscSort(List<T> data, Function<? super T, ? extends U> keyExtractor) {
|
||||
return data.stream().sorted(Comparator.comparing(keyExtractor)).toList();
|
||||
}
|
||||
|
||||
@@ -78,9 +76,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
* @param <U> /
|
||||
* @return /
|
||||
*/
|
||||
public static <T, U extends Comparable<? super U>> List<T> streamDescSort(
|
||||
List<T> data,
|
||||
Function<? super T, ? extends U> keyExtractor) {
|
||||
public static <T, U extends Comparable<? super U>> List<T> streamDescSort(List<T> data, Function<? super T, ? extends U> keyExtractor) {
|
||||
return data.stream().sorted(Comparator.comparing(keyExtractor).reversed()).toList();
|
||||
}
|
||||
|
||||
@@ -97,10 +93,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
* @param <U> /
|
||||
* @return /
|
||||
*/
|
||||
public static <T, K, U> Map<K, U> streamToMap(
|
||||
List<T> data,
|
||||
Function<? super T, ? extends K> keyMapper,
|
||||
Function<? super T, ? extends U> valueMapper) {
|
||||
public static <T, K, U> Map<K, U> streamToMap(List<T> data, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
|
||||
// 根据key去重再并流
|
||||
return streamDistinct(data, keyMapper).stream().collect(Collectors.toMap(keyMapper, valueMapper));
|
||||
}
|
||||
@@ -150,7 +143,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
try {
|
||||
Field field = m.getClass().getDeclaredField(elementName);
|
||||
field.setAccessible(true);
|
||||
that = (BigDecimal) field.get(m);
|
||||
that = (BigDecimal)field.get(m);
|
||||
} catch (Exception e) {
|
||||
// 忽略异常
|
||||
that = BigDecimal.ZERO;
|
||||
@@ -192,10 +185,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
* @return /
|
||||
*/
|
||||
public static BigDecimal streamBigDecimalAvg(List<BigDecimal> data) {
|
||||
return data.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add)
|
||||
.divide(BigDecimal.valueOf(data.size()), 6, RoundingMode.FLOOR);
|
||||
return data.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(data.size()), 6, RoundingMode.FLOOR);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
@@ -214,8 +204,7 @@ public final class CsCollUtil extends cn.hutool.core.collection.CollUtil {
|
||||
System.out.println(JSON.toJSONString(selectOptions2));
|
||||
List<CsSelectOptionVo> selectOptions3 = CsCollUtil.streamDistinct(testData, CsSelectOptionVo::getValue);
|
||||
System.out.println(JSON.toJSONString(selectOptions3));
|
||||
Map<String, String> selectMap1 =
|
||||
CsCollUtil.streamToMap(testData, CsSelectOptionVo::getValue, CsSelectOptionVo::getLabel);
|
||||
Map<String, String> selectMap1 = CsCollUtil.streamToMap(testData, CsSelectOptionVo::getValue, CsSelectOptionVo::getLabel);
|
||||
System.out.println(JSON.toJSONString(selectMap1));
|
||||
// 这只是一个示范
|
||||
BigDecimal total1 = CsCollUtil.streamBigDecimalAdd(testData, "value");
|
||||
|
||||
+1
-1
@@ -89,7 +89,7 @@ public final class CsDesEncryptUtil {
|
||||
byte[] b2 = new byte[b.length / 2];
|
||||
for (int n = 0; n < b.length; n += size) {
|
||||
String item = new String(b, n, 2);
|
||||
b2[n / 2] = (byte) Integer.parseInt(item, 16);
|
||||
b2[n / 2] = (byte)Integer.parseInt(item, 16);
|
||||
}
|
||||
return b2;
|
||||
}
|
||||
|
||||
+52
-61
@@ -87,13 +87,6 @@ public final class CsDistributedIdUtil {
|
||||
*/
|
||||
private final AtomicLong lastTimestamp = new AtomicLong(-1L);
|
||||
|
||||
/**
|
||||
* 单例实例持有者类
|
||||
*/
|
||||
private static class InstanceHolder {
|
||||
private static final CsDistributedIdUtil INSTANCE = new CsDistributedIdUtil(20, 12, 5, 5, 12);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数, 初始化数据中心 ID 和机器 ID
|
||||
*
|
||||
@@ -103,12 +96,7 @@ public final class CsDistributedIdUtil {
|
||||
* @param workerIdBits 机器 ID 所占位数
|
||||
* @param sequenceBits 序列号所占位数
|
||||
*/
|
||||
public CsDistributedIdUtil(
|
||||
long dataCenterId,
|
||||
long workerId,
|
||||
long dataCenterIdBits,
|
||||
long workerIdBits,
|
||||
long sequenceBits) {
|
||||
public CsDistributedIdUtil(long dataCenterId, long workerId, long dataCenterIdBits, long workerIdBits, long sequenceBits) {
|
||||
this.dataCenterIdBits = dataCenterIdBits;
|
||||
this.workerIdBits = workerIdBits;
|
||||
this.sequenceBits = sequenceBits;
|
||||
@@ -131,54 +119,6 @@ public final class CsDistributedIdUtil {
|
||||
this.workerId = workerId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成下一个分布式 ID
|
||||
*
|
||||
* @return 生成的分布式 ID
|
||||
*/
|
||||
public long nextId() {
|
||||
long currentTimestamp = System.currentTimeMillis();
|
||||
|
||||
// 如果当前时间戳小于上一次生成 ID 的时间戳, 说明时钟回拨,抛出异常
|
||||
if (currentTimestamp < lastTimestamp.get()) {
|
||||
throw new BadRequestException(
|
||||
"Clock moved backwards. Refusing to generate id for " + (lastTimestamp.get() - currentTimestamp) +
|
||||
" milliseconds");
|
||||
}
|
||||
|
||||
long lastTimestampValue = lastTimestamp.get();
|
||||
if (currentTimestamp == lastTimestampValue) {
|
||||
// 同一毫秒内,序列号自增
|
||||
long seq = sequence.incrementAndGet() & sequenceMask;
|
||||
if (seq == 0) {
|
||||
// 序列号溢出,等待下一毫秒
|
||||
currentTimestamp = waitNextMillis(lastTimestampValue);
|
||||
}
|
||||
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) |
|
||||
(workerId << workerIdShift) | seq;
|
||||
} else {
|
||||
// 时间戳改变,重置序列号
|
||||
sequence.set(0L);
|
||||
lastTimestamp.set(currentTimestamp);
|
||||
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) |
|
||||
(workerId << workerIdShift);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待下一毫秒
|
||||
*
|
||||
* @param lastTimestamp 上一次生成 ID 的时间戳
|
||||
* @return 当前时间戳
|
||||
*/
|
||||
private long waitNextMillis(long lastTimestamp) {
|
||||
long timestamp = System.currentTimeMillis();
|
||||
while (timestamp <= lastTimestamp) {
|
||||
timestamp = System.currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单例实例的下一个分布式 ID
|
||||
*
|
||||
@@ -203,4 +143,55 @@ public final class CsDistributedIdUtil {
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成下一个分布式 ID
|
||||
*
|
||||
* @return 生成的分布式 ID
|
||||
*/
|
||||
public long nextId() {
|
||||
long currentTimestamp = System.currentTimeMillis();
|
||||
|
||||
// 如果当前时间戳小于上一次生成 ID 的时间戳, 说明时钟回拨,抛出异常
|
||||
if (currentTimestamp < lastTimestamp.get()) {
|
||||
throw new BadRequestException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp.get() - currentTimestamp) + " milliseconds");
|
||||
}
|
||||
|
||||
long lastTimestampValue = lastTimestamp.get();
|
||||
if (currentTimestamp == lastTimestampValue) {
|
||||
// 同一毫秒内,序列号自增
|
||||
long seq = sequence.incrementAndGet() & sequenceMask;
|
||||
if (seq == 0) {
|
||||
// 序列号溢出,等待下一毫秒
|
||||
currentTimestamp = waitNextMillis(lastTimestampValue);
|
||||
}
|
||||
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift) | seq;
|
||||
} else {
|
||||
// 时间戳改变,重置序列号
|
||||
sequence.set(0L);
|
||||
lastTimestamp.set(currentTimestamp);
|
||||
return ((currentTimestamp - START_TIMESTAMP) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待下一毫秒
|
||||
*
|
||||
* @param lastTimestamp 上一次生成 ID 的时间戳
|
||||
* @return 当前时间戳
|
||||
*/
|
||||
private long waitNextMillis(long lastTimestamp) {
|
||||
long timestamp = System.currentTimeMillis();
|
||||
while (timestamp <= lastTimestamp) {
|
||||
timestamp = System.currentTimeMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单例实例持有者类
|
||||
*/
|
||||
private static class InstanceHolder {
|
||||
private static final CsDistributedIdUtil INSTANCE = new CsDistributedIdUtil(20, 12, 5, 5, 12);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-16
@@ -41,7 +41,6 @@ import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static cn.odboy.constant.SystemConst.*;
|
||||
|
||||
@@ -108,13 +107,13 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
String resultSize;
|
||||
if (size / GB >= 1) {
|
||||
//如果当前Byte的值大于等于1GB
|
||||
resultSize = DF.format(size / (float) GB) + " GB";
|
||||
resultSize = DF.format(size / (float)GB) + " GB";
|
||||
} else if (size / MB >= 1) {
|
||||
//如果当前Byte的值大于等于1MB
|
||||
resultSize = DF.format(size / (float) MB) + " MB";
|
||||
resultSize = DF.format(size / (float)MB) + " MB";
|
||||
} else if (size / KB >= 1) {
|
||||
//如果当前Byte的值大于等于1KB
|
||||
resultSize = DF.format(size / (float) KB) + " KB";
|
||||
resultSize = DF.format(size / (float)KB) + " KB";
|
||||
} else {
|
||||
resultSize = size + " B";
|
||||
}
|
||||
@@ -190,9 +189,8 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
map.forEach((key, value) -> {
|
||||
if (value instanceof String strValue) {
|
||||
// 检查并处理以特殊字符开头的值
|
||||
if (strValue.startsWith(SYMBOL_EQUAL) || strValue.startsWith(SYMBOL_ADD) ||
|
||||
strValue.startsWith(SYMBOL_SUBTRACT) || strValue.startsWith(
|
||||
SYMBOL_AT)) {
|
||||
if (strValue.startsWith(SYMBOL_EQUAL) || strValue.startsWith(SYMBOL_ADD) || strValue.startsWith(SYMBOL_SUBTRACT) || strValue.startsWith(
|
||||
SYMBOL_AT)) {
|
||||
// 添加单引号前缀
|
||||
strValue = "'" + strValue;
|
||||
}
|
||||
@@ -205,7 +203,7 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
}).toList();
|
||||
// 一次性写出内容, 使用默认样式,强制输出标题
|
||||
writer.write(sanitizedList, true);
|
||||
SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();
|
||||
SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();
|
||||
//上面需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法
|
||||
sheet.trackAllColumnsForAutoSizing();
|
||||
//列宽自适应
|
||||
@@ -277,7 +275,7 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
* 获取文件字节数组
|
||||
*/
|
||||
private static byte[] getByte(File file) {
|
||||
byte[] b = new byte[(int) file.length()];
|
||||
byte[] b = new byte[(int)file.length()];
|
||||
InputStream in = null;
|
||||
try {
|
||||
in = Files.newInputStream(file.toPath());
|
||||
@@ -324,11 +322,7 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
* @param response /
|
||||
* @param file /
|
||||
*/
|
||||
public static void downloadFile(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
File file,
|
||||
boolean deleteOnExit) {
|
||||
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
|
||||
response.setCharacterEncoding(request.getCharacterEncoding());
|
||||
response.setContentType("application/octet-stream");
|
||||
FileInputStream fis = null;
|
||||
@@ -385,8 +379,7 @@ public final class CsFileUtil extends cn.hutool.core.io.FileUtil {
|
||||
fileName = fileName.replaceAll("^\\.+/", "");
|
||||
|
||||
// 保留文件名中最后一个 "." 字符,过滤掉其他 "."
|
||||
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
|
||||
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
|
||||
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") + fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
@@ -55,12 +55,10 @@ public final class CsIPUtil {
|
||||
try {
|
||||
InetAddress candidateAddress = null;
|
||||
// 遍历所有的网络接口
|
||||
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
interfaces.hasMoreElements(); ) {
|
||||
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
|
||||
NetworkInterface anInterface = interfaces.nextElement();
|
||||
// 在所有的接口下再遍历IP
|
||||
for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses();
|
||||
inetAddresses.hasMoreElements(); ) {
|
||||
for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
|
||||
InetAddress inetAddr = inetAddresses.nextElement();
|
||||
// 排除loopback类型地址
|
||||
if (!inetAddr.isLoopbackAddress()) {
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ import java.util.Set;
|
||||
*/
|
||||
public class CsReturnValueHandleUtil {
|
||||
public static Object getDefaultValue(ProceedingJoinPoint joinPoint) {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
// 获取目标方法的返回值类型
|
||||
Class<?> returnType = method.getReturnType();
|
||||
|
||||
+2
-2
@@ -183,8 +183,8 @@ public final class CsRsaEncryptUtil {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(1024);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
|
||||
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
|
||||
RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
|
||||
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
|
||||
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
|
||||
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
|
||||
return new RsaKeyPair(publicKeyString, privateKeyString);
|
||||
|
||||
+1
-3
@@ -46,9 +46,7 @@ public final class CsValidUtil {
|
||||
public static <T> void validate(T object) {
|
||||
Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object, Default.class);
|
||||
if (!violations.isEmpty()) {
|
||||
throw new BadRequestException(violations.stream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.joining(",")));
|
||||
throw new BadRequestException(violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user