20 Commits
1.0.0 ... 1.6.2

Author SHA1 Message Date
yhl452493373
f039ed30c9 增加releaseBefore、releaseAfter、clearBefore、clearAfter方法 2022-02-21 10:26:29 +08:00
yhl452493373
f02fdf5a53 更新README 2022-02-16 17:38:36 +08:00
yhl452493373
464b99a09b 调整创建表时key、type、seq的长度,分别为64,64,20,避免出现“Specified key was too long; max key length is 767 bytes”问题 2022-02-16 17:36:50 +08:00
yhl452493373
6a5a8111ee 变更测试使用的字段名 2022-02-16 10:47:57 +08:00
yhl452493373
1accb4b066 变更测试使用的字段名 2022-02-16 10:41:22 +08:00
yhl452493373
c865be0918 更新README 2022-02-15 13:37:54 +08:00
yhl452493373
011e37c1a3 1、增加 clear()和clear(begin,end)方法,用于在某些情况下清理unlock和unused表,避免他们越来越大 2022-02-15 09:47:37 +08:00
yhl452493373
a4e5017b60 升级junit 2022-02-14 17:20:23 +08:00
yhl452493373
19fb15bd03 1、Generator中占位符部分转到FormatPlaceholder枚举中,规范其代码
2、SequencesGenerator中,基础配置转到BaseConfig,该类为单例,便于其他地方调用
3、Generator中,format方法重构,增加不需要minLength参数的方法,minLength参数从BaseConfig单例中或
4、Sequences中,format方法重构,增加不需要minLength参数的方法,minLength参数从BaseConfig单例中或
2022-02-14 16:23:24 +08:00
yhl452493373
956e707399 增加默认序号类型 2022-02-11 14:45:36 +08:00
yhl452493373
6bfcb1fd51 事务管理器由new JdbcTransactionManager(datasource)改为new DataSourceTransactionManager(datasource),以支持spring4 2022-02-11 14:26:36 +08:00
yhl452493373
f6750280d8 更新 README 2022-02-11 13:58:42 +08:00
yhl452493373
0fa5cc1e7e 增加 Sequences parse(String formatted, String pattern)方法,用于根据格式反解析格式化后的字符串为序列号对象 2022-02-11 13:57:12 +08:00
yhl452493373
54e2f9dffb 增加 String format(Sequences sequences, Integer minLength, String pattern)方法 2022-02-10 18:05:49 +08:00
yhl452493373
1a9a158126 update README 2022-02-10 11:28:52 +08:00
yhl452493373
81c9babb40 增加手动释放指定序号功能 2022-02-10 11:23:08 +08:00
杨黄林
c77088a7f5 更新 README.md 2022-02-01 15:36:38 +08:00
c6d828bf0f 更新 'README.md' 2022-02-01 07:31:38 +00:00
杨黄林
8046474df7 更新 README.md 2022-02-01 15:29:12 +08:00
杨黄林
e45e75c644 变更包名 2022-02-01 15:22:37 +08:00
22 changed files with 1399 additions and 560 deletions

243
README.md
View File

@@ -8,17 +8,17 @@
使用方法:
+ 在项目中放置jar包的地方把seq-1.0.0.jar、seq-1.0.0-sources.jar、seq-1.0.0-pom.xml复制过去
+ 在项目中放置jar包的地方把seq-1.6.2.jar、seq-1.6.2-sources.jar、seq-1.6.2-pom.xml复制过去
+ 在pom.xml中增加以下内容然后执行maven命令mvn clean
```xml
<build>
<project>
<dependencies>
<dependency>
<groupId>com.cdhncy</groupId>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.0.0</version>
<version>1.6.2</version>
<exclusions>
<!-- 如若你项目中有引用spring-jdbc则需要排除seq的jdbc依赖 -->
<exclusion>
@@ -34,6 +34,8 @@
</dependency>
</dependencies>
<build>
<plugins>
<!-- 每次执行mvn clean时自动安装指定的jar包 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -48,31 +50,33 @@
</goals>
<configuration>
<!-- ${project.basedir}表示当前项目的根目录 -->
<file>${project.basedir}/lib/seq-1.0.0.jar</file>
<pomFile>${pom.basedir}/lib/seq-1.0.0-pom.xml</pomFile>
<sources>${project.basedir}/lib/seq-1.0.0-sources.jar</sources>
<file>${project.basedir}/lib/seq-1.6.2.jar</file>
<pomFile>${project.basedir}/lib/seq-1.6.2-pom.xml</pomFile>
<sources>${project.basedir}/lib/seq-1.6.2-sources.jar</sources>
<repositoryLayout>default</repositoryLayout>
<groupId>com.cdhncy</groupId>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.0.0</version>
<version>1.6.2</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
+ springboot中配置方式一优先直接注入已有jdbcTemplate和transactionTemplate
```java
package com.yang.springseq.config;
package com.yanghuanglin.springseq.baseConfig;
import com.cdhncy.seq.config.GeneratorConfig;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.generator.Generator;
import com.cdhncy.seq.generator.impl.SequencesGenerator;
import com.yanghuanglin.seq.baseConfig.GeneratorConfig;
import com.yanghuanglin.seq.baseConfig.TableConfig;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -103,11 +107,11 @@ public class SeqGeneratorConfig {
public TableConfig tableConfig() {
TableConfig tableConfig = new TableConfig();
//自定义表名、字段名
//tableConfig.setTable("sequences");
//tableConfig.setKeyColumn("SEQUENCE_KEY");
//tableConfig.setTypeColumn("SEQUENCE_TYPE");
//tableConfig.setSeqColumn("SEQUENCE_NEXT_ID");
//tableConfig.setCreateTimeColumn("CREATE_TIME");
tableConfig.setTable("sequences");
tableConfig.setKeyColumn("SEQUENCE_KEY");
tableConfig.setTypeColumn("SEQUENCE_TYPE");
tableConfig.setSeqColumn("NEXT_ID");
tableConfig.setCreateTimeColumn("CREATE_TIME");
return tableConfig;
}
@@ -138,16 +142,14 @@ public class SeqGeneratorConfig {
+ springboot中配置方式二注入已有的dataSource或自行构建dataSource通过dataSource自动生成jdbcTemplate和transactionTemplate
```java
package com.yang.springseq.config;
package com.yanghuanglin.springseq.baseConfig;
import com.cdhncy.seq.config.GeneratorConfig;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.generator.Generator;
import com.cdhncy.seq.generator.impl.SequencesGenerator;
import com.yanghuanglin.seq.baseConfig.GeneratorConfig;
import com.yanghuanglin.seq.baseConfig.TableConfig;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
import javax.sql.DataSource;
@@ -170,11 +172,11 @@ public class SeqGeneratorConfig {
public TableConfig tableConfig() {
TableConfig tableConfig = new TableConfig();
//自定义表名、字段名
//tableConfig.setTable("sequences");
//tableConfig.setKeyColumn("SEQUENCE_KEY");
//tableConfig.setTypeColumn("SEQUENCE_TYPE");
//tableConfig.setSeqColumn("SEQUENCE_NEXT_ID");
//tableConfig.setCreateTimeColumn("CREATE_TIME");
tableConfig.setTable("sequences");
tableConfig.setKeyColumn("SEQUENCE_KEY");
tableConfig.setTypeColumn("SEQUENCE_TYPE");
tableConfig.setSeqColumn("NEXT_ID");
tableConfig.setCreateTimeColumn("CREATE_TIME");
return tableConfig;
}
@@ -182,6 +184,7 @@ public class SeqGeneratorConfig {
* 序号生成器配置类
* @param tableConfig 序号表配置类
*/
@DependsOn("tableConfig")
@Bean
public GeneratorConfig generatorConfig(TableConfig tableConfig) {
GeneratorConfig generatorConfig = new GeneratorConfig();
@@ -193,6 +196,7 @@ public class SeqGeneratorConfig {
* 注册序号生成器类
* @param generatorConfig 序号生成器配置类
*/
@DependsOn("generatorConfig")
@Bean
public Generator generator(GeneratorConfig generatorConfig) {
return new SequencesGenerator(generatorConfig);
@@ -203,10 +207,10 @@ public class SeqGeneratorConfig {
+ 使用:
```java
package com.yang.springseq.config;
package com.yanghuanglin.springseq.baseConfig;
import com.cdhncy.seq.generator.Generator;
import com.cdhncy.seq.po.Sequences;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.po.Sequences;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@@ -270,47 +274,48 @@ TableConfig配置项通过set方法设置一般不用改如果已有相
GeneratorConfig配置项通过set方法设置
| 配置项 | 类型 | 默认值 | 说明 |
|---------------------|------------------------------------------------------------------|------------------|----------|
|---------------------|------------------------------------------------------------------|------------------|------------------|
| dataSource | javax.sql.DataSource | null | 数据源 |
| jdbcTemplate | org.springframework.jdbc.core.JdbcTemplate | null | 数据库操作模板 |
| transactionTemplate | org.springframework.jdbc.core.JdbcTemplate | null | 事务操作模板 |
| transactionManager | org.springframework.jdbc.datasource.DataSourceTransactionManager | null | 事务管理器 |
| autoCreate | Boolean | true | 开启自动建表 |
| step | Integer | 1 | 序号增加时的步长 |
| tableConfig | com.cdhncy.seq.config.TableConfig | TableConfig的默认配置 | 表配置 |
| type | String | DEFAULT | 默认序号类型 |
| minLength | Integer | 1 | 默认序号格式化后长度,不足的补零 |
| tableConfig | com.yanghuanglin.seq.baseConfig.TableConfig | TableConfig的默认配置 | 表配置 |
以上配置中jdbcTemplate和transactionTemplate优先级最高如果jdbcTemplate、transactionTemplate、dataSource、transactionManager同时配置则dataSource和transactionManager无效
进行这几种组合dataSource+autoCreate+step+tableConfigjdbcTemplate+transactionTemplate+autoCreate+step+tableConfigjdbcTemplate+transactionManager+autoCreate+step+tableConfig
进行这几种组合dataSource+autoCreate+step+minLength+tableConfigjdbcTemplate+transactionTemplate+autoCreate+step+minLength+tableConfigjdbcTemplate+transactionManager+autoCreate+step+minLength+tableConfig
---
Generator方法如下
```java
package com.cdhncy.seq.generator;
package com.yanghuanglin.seq.generator;
import com.cdhncy.seq.po.Sequences;
import com.cdhncy.seq.po.SequencesUnlock;
import com.cdhncy.seq.po.SequencesUnused;
import com.yanghuanglin.seq.config.BaseConfig;
import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.enums.FormatPlaceholder;
import com.yanghuanglin.seq.po.Sequences;
import com.yanghuanglin.seq.po.SequencesUnlock;
import com.yanghuanglin.seq.po.SequencesUnused;
import java.util.Date;
public interface Generator {
/**
* 序号格式字符中的年
* 根据传入的key和type生成可用的序号对象。
* <p/>
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找不到记录说明该组合的序号对象还未初次生成返回的是seq为step的序号对象该对象数据会写入到{@link SequencesUnlock}中。
* <p/>
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @return 可用的序号对象
*/
String YEAR = "#year#";
/**
* 序号格式字符中的月
*/
String MONTH = "#month#";
/**
* 序号格式字符中的日
*/
String DAY = "#day#";
/**
* 序号格式字符中的格式化后的序号
*/
String SEQ = "#seq#";
Sequences generate(String key);
/**
* 根据传入的key和type生成可用的序号对象。
@@ -338,10 +343,48 @@ public interface Generator {
*/
String generate(String key, String type, Integer minLength);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Sequences sequences, String pattern);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param minLength 序号数字最小长度
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Sequences sequences, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR#getPlaceholder()}(当前年份)、{@link FormatPlaceholder#MONTH#getPlaceholder()}(当前月份)、{@link FormatPlaceholder#DAY#getPlaceholder()}(当前日期)、{@link FormatPlaceholder#SEQ#getPlaceholder()}(生成的字符串序号)四个变量
* <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param pattern 格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link #YEAR}(当前年份)、{@link #MONTH}(当前月份)、{@link #DAY}(当前日期)、{@link #SEQ}(生成的字符串序号)四个变量
* pattern支持{@link FormatPlaceholder#YEAR}}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/>
@@ -350,14 +393,30 @@ public interface Generator {
* @param seq 需要格式化的序号
* @param minLength 序号最小长度,不足的会补零
* @param pattern 格式
* @return 格式化后的字符串
* @return 格式化后的序号字符串
*/
String format(Long seq, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link #YEAR}(当前年份)、{@link #MONTH}(当前月份)、{@link #DAY}(当前日期)、{@link #SEQ}(生成的字符串序号)四个变量
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
@@ -366,11 +425,30 @@ public interface Generator {
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param minLength 序号最小长度,不足的会补零
* @param pattern 格式
* @return 格式化后的字符串
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, Integer minLength, String pattern);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
* 注意:序号格式和格式化后的字符串占位一定要匹配。如:处〔#year##month#10801第#seq#号 对应 处20220210801第10001号而不能对应 处2022021110801第10001号
*
* @param formatted 格式化后的序号字符串
* @param pattern 序号格式
* @return 包含了序号字符串对应年如果有、月如果有、日如果有、序号的序号对象其key需要根据情况手动设置type为{@link GeneratorConfig#getType()}的默认值
*/
Sequences parse(String formatted, String pattern);
/**
* 锁定指定序号,在序号生成后,调用该序号的逻辑完成后需要执行此方法
* <p/>
@@ -399,6 +477,51 @@ public interface Generator {
* @param end 结束时间
*/
void release(Date begin, Date end);
/**
* 释放从开始时间开始,到现在时间之间未使用的序号。结束时间为方法执行时的时间
*
* @param begin 开始时间
*/
void releaseAfter(Date begin);
/**
* 释放结束时间以前的序号
*
* @param end 结束时间
*/
void releaseBefore(Date end);
/**
* 释放指定序号。一般用于业务对象删除后,对应序号需要回收使用时。
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
*/
void release(Sequences sequences);
/**
* 清空所有闲置序号和未锁定序号
*/
void clear();
/**
* 清空指定时间段内闲置序号和未锁定序号
*/
void clear(Date begin, Date end);
/**
* 清空从开始时间到限制时间之间闲置序号和未锁定序号,结束时间为方法执行时的时间
*
* @param begin 开始时间
*/
void clearAfter(Date begin);
/**
* 清空结束时间之前的限制序号和未锁定序号
*
* @param end 结束时间
*/
void clearBefore(Date end);
}
```

View File

@@ -2,9 +2,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cdhncy</groupId>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.0.0</version>
<version>1.6.2</version>
<name>seq</name>
<description>seq</description>
<properties>
@@ -24,7 +24,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -34,6 +34,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>8</source>
<target>8</target>

View File

@@ -1,114 +0,0 @@
package com.cdhncy.seq.generator;
import com.cdhncy.seq.po.Sequences;
import com.cdhncy.seq.po.SequencesUnlock;
import com.cdhncy.seq.po.SequencesUnused;
import java.util.Date;
public interface Generator {
/**
* 序号格式字符中的年
*/
String YEAR = "#year#";
/**
* 序号格式字符中的月
*/
String MONTH = "#month#";
/**
* 序号格式字符中的日
*/
String DAY = "#day#";
/**
* 序号格式字符中的格式化后的序号
*/
String SEQ = "#seq#";
/**
* 根据传入的key和type生成可用的序号对象。
* <p/>
* 如果根据key和type在{@link Sequences}中找不到记录说明该组合的序号对象还未初次生成返回的是seq为step的序号对象该对象数据会写入到{@link SequencesUnlock}中。
* <p/>
* 如果根据key和type在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param type 序号类型
* @return 可用的序号对象
*/
Sequences generate(String key, String type);
/**
* 返回根据{@link #generate(String, String)}得到的序号对象,补零后的序号字符串
* <p/>
* 如生成的为3而minLength为5则返回的是00003
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @return 补零后的字符串
*/
String generate(String key, String type, Integer minLength);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link #YEAR}(当前年份)、{@link #MONTH}(当前月份)、{@link #DAY}(当前日期)、{@link #SEQ}(生成的字符串序号)四个变量
* <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param minLength 序号最小长度,不足的会补零
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Long seq, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link #YEAR}(当前年份)、{@link #MONTH}(当前月份)、{@link #DAY}(当前日期)、{@link #SEQ}(生成的字符串序号)四个变量
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param minLength 序号最小长度,不足的会补零
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Long seq, String start, Integer minLength, String pattern);
/**
* 锁定指定序号,在序号生成后,调用该序号的逻辑完成后需要执行此方法
* <p/>
* 如办理案件时,先调用{@link #generate(String, String)}或者{@link #generate(String, String, Integer)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* <p/>
* 注意,此处的锁定非数据库中锁定,而是{@link SequencesUnused}和{@link SequencesUnlock}中均不存在key、type、seq相同的记录视为锁定。因此此处实际是把这两个表中的记录均删除了
*
* @param sequences 需要锁定的序号
* @return 锁定结果
*/
boolean lock(Sequences sequences);
/**
* 释放所有未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*/
void release();
/**
* 释放指定时间段内未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*
* @param begin 开始时间
* @param end 结束时间
*/
void release(Date begin, Date end);
}

View File

@@ -1,188 +0,0 @@
package com.cdhncy.seq.generator.impl;
import com.cdhncy.seq.config.GeneratorConfig;
import com.cdhncy.seq.dao.SequencesDao;
import com.cdhncy.seq.dao.SequencesUnusedDao;
import com.cdhncy.seq.dao.SequencesUnlockDao;
import com.cdhncy.seq.dao.impl.SequencesDaoImpl;
import com.cdhncy.seq.dao.impl.SequencesUnusedDaoImpl;
import com.cdhncy.seq.dao.impl.SequencesUnlockDaoImpl;
import com.cdhncy.seq.po.Sequences;
import com.cdhncy.seq.po.SequencesUnused;
import com.cdhncy.seq.po.SequencesUnlock;
import com.cdhncy.seq.generator.Generator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
import java.util.*;
public class SequencesGenerator implements Generator {
private final TransactionTemplate transactionTemplate;
private final SequencesDao sequencesDao;
private final SequencesUnusedDao sequencesUnusedDao;
private final SequencesUnlockDao sequencesUnlockDao;
private final Integer step;
public SequencesGenerator(GeneratorConfig generatorConfig) {
//数据库操作模板
JdbcTemplate jdbcTemplate = generatorConfig.getJdbcTemplate();
if (jdbcTemplate == null) {
//数据源
DataSource dataSource = generatorConfig.getDataSource();
if (dataSource == null)
//若数据库操作模板为空,也没有配置数据源,则抛出异常
throw new NullPointerException("数据源不能为空");
//否则以数据源创建数据库操作模板
jdbcTemplate = new JdbcTemplate(dataSource);
}
if (generatorConfig.getTransactionTemplate() == null) {
//若没有配置事务操作模板,则从配置中取事务管理器
DataSourceTransactionManager transactionManager = generatorConfig.getTransactionManager();
if (transactionManager == null) {
//若未配置事务管理器,则通过数据源新建
DataSource dataSource = jdbcTemplate.getDataSource();
if (dataSource == null)
throw new NullPointerException("数据源不能为空");
transactionManager = new JdbcTransactionManager(dataSource);
}
//通过事务管理器创建事务操作模板
transactionTemplate = new TransactionTemplate(transactionManager);
} else {
//获取事务操作模板
transactionTemplate = generatorConfig.getTransactionTemplate();
}
this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.step = generatorConfig.getStep();
autoCreateTable(generatorConfig.getAutoCreate());
}
/**
* 自动创建需要的表
*/
private void autoCreateTable(Boolean autoCreate) {
if (!autoCreate)
return;
this.sequencesDao.createTable();
this.sequencesUnusedDao.createTable();
this.sequencesUnlockDao.createTable();
}
@Override
public synchronized Sequences generate(String key, String type) {
return transactionTemplate.execute(status -> {
try {
//根据传入的key和type新生成查询条件对象
Sequences condition = new Sequences(key, type);
//找到正在使用的最大序号
Sequences sequences = sequencesDao.find(condition);
if (sequences == null) {
//不存在说明还没生成将新生成的入库此时序号为默认的0
sequences = condition;
sequencesDao.save(sequences);
}
//根据传入的key和type查找空闲编号最小的一个
SequencesUnused conditionIdle = new SequencesUnused(condition);
SequencesUnused sequencesUnused = sequencesUnusedDao.findMinSeq(conditionIdle);
if (sequencesUnused == null) {
//空闲编号不存在,说明是未生成过,序号需要增加后直接使用,同时将新生成的写入到使用中表
sequences.increase(step);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequences);
sequencesUnlock.setCreateTime(new Date());
sequencesDao.update(sequences);
sequencesUnlockDao.save(sequencesUnlock);
} else {
//空闲编号存在,说明已经生成过,序号不需要增加,直接使用。同时将该空闲编号移动到使用中表
sequences = new Sequences(sequencesUnused);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequencesUnused);
sequencesUnlock.setCreateTime(new Date());
sequencesUnlockDao.save(sequencesUnlock);
sequencesUnusedDao.delete(sequencesUnused);
}
return sequences;
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return null;
}
});
}
@Override
public synchronized String generate(String key, String type, Integer minLength) {
Sequences sequences = this.generate(key, type);
if (sequences == null)
return null;
return sequences.format(minLength);
}
@Override
public String format(Long seq, Integer minLength, String pattern) {
return format(seq, null, minLength, pattern);
}
@Override
public String format(Long seq, String start, Integer minLength, String pattern) {
if (start == null)
start = "";
String seqString = start + new Sequences(seq).format(minLength);
Calendar calendar = Calendar.getInstance();
pattern = pattern.replaceAll(Generator.YEAR, String.valueOf(calendar.get(Calendar.YEAR)));
pattern = pattern.replaceAll(Generator.MONTH, String.format("%02d", calendar.get(Calendar.MONTH) + 1));
pattern = pattern.replaceAll(Generator.DAY, String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
pattern = pattern.replaceAll(Generator.SEQ, seqString);
return pattern;
}
@Override
public synchronized boolean lock(Sequences sequences) {
SequencesUnlock condition = new SequencesUnlock(sequences);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
return sequencesUnlockDao.delete(condition);
}
@Override
public void release() {
//列出所有使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listAll();
List<SequencesUnused> sequencesUnusedList = new ArrayList<>();
for (SequencesUnlock sequencesUnlock : sequencesUnlockList) {
sequencesUnusedList.add(new SequencesUnused(sequencesUnlock));
}
//将使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除所有使用中表的数据
sequencesUnlockDao.deleteAll();
}
@Override
public void release(Date begin, Date end) {
//列出指定时间段内使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listByDate(begin, end);
List<SequencesUnused> sequencesUnusedList = new ArrayList<>();
for (SequencesUnlock sequencesUnlock : sequencesUnlockList) {
sequencesUnusedList.add(new SequencesUnused(sequencesUnlock));
}
//将指定时间段内使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除指定时间段内使用中表的数据
sequencesUnlockDao.deleteByDate(begin, end);
}
}

View File

@@ -1,88 +0,0 @@
package com.cdhncy.seq.po;
/**
* 当前序号
*
* @author yanghuanglin
* @since 2022/1/28
*/
public class Sequences {
/**
* 需要生成序号的key和type组成唯一主键
*/
protected String key;
/**
* 需要生成序号的类型和key组成唯一主键
*/
protected String type;
/**
* 默认序号
*/
protected Long seq = 0L;
public Sequences() {
}
public Sequences(Long seq) {
this.seq = seq;
}
public Sequences(String key, String type) {
this.key = key;
this.type = type;
}
public Sequences(SequencesUnused sequencesUnused) {
this.key = sequencesUnused.getKey();
this.type = sequencesUnused.getType();
this.seq = sequencesUnused.getSeq();
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSeq() {
return seq;
}
public void setSeq(Long seq) {
this.seq = seq;
}
/**
* 将序号增加指定步长
*
* @param step 步长
*/
public void increase(Integer step) {
this.seq += step;
}
/**
* 序号补零
*
* @param minLength 最小长度,低于此长度,会填充零
* @return 补零后的序号
*/
public String format(Integer minLength) {
if (minLength != null)
return String.format("%0" + minLength + "d", this.seq);
return String.valueOf(this.seq);
}
}

View File

@@ -1,19 +0,0 @@
package com.cdhncy.seq.po;
/**
* 闲置序号
*
* @author yanghuanglin
* @since 2022/1/28
*/
public class SequencesUnused extends Sequences {
public SequencesUnused() {
}
public SequencesUnused(Sequences sequences) {
this.key = sequences.getKey();
this.type = sequences.getType();
this.seq = sequences.getSeq();
}
}

View File

@@ -0,0 +1,170 @@
package com.yanghuanglin.seq.config;
import com.yanghuanglin.seq.dao.SequencesDao;
import com.yanghuanglin.seq.dao.SequencesUnlockDao;
import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.dao.impl.SequencesDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnlockDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnusedDaoImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
/**
* 生成器最后的基础配置信息,单例模式,便于其他地方调用
*
* @author yanghuanglin
* @since 2022/2/14
*/
public class BaseConfig {
private static volatile BaseConfig instance;
private TransactionTemplate transactionTemplate;
private SequencesDao sequencesDao;
private SequencesUnusedDao sequencesUnusedDao;
private SequencesUnlockDao sequencesUnlockDao;
private Integer step;
private String type;
private Integer minLength;
private BaseConfig() {
}
public static BaseConfig getInstance() {
if (instance == null) {
synchronized (BaseConfig.class) {
if (instance == null) {
instance = new BaseConfig();
}
}
}
return instance;
}
public static BaseConfig getInstance(GeneratorConfig generatorConfig) {
if (instance == null) {
synchronized (BaseConfig.class) {
if (instance == null) {
instance = new BaseConfig();
}
}
}
instance.init(generatorConfig);
return instance;
}
public static void setInstance(BaseConfig instance) {
BaseConfig.instance = instance;
}
public TransactionTemplate getTransactionTemplate() {
if (transactionTemplate == null)
throw new NullPointerException("请先初始化BaseConfig");
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
public SequencesDao getSequencesDao() {
if (sequencesDao == null)
throw new NullPointerException("请先初始化BaseConfig");
return sequencesDao;
}
public void setSequencesDao(SequencesDao sequencesDao) {
this.sequencesDao = sequencesDao;
}
public SequencesUnusedDao getSequencesUnusedDao() {
if (sequencesUnusedDao == null)
throw new NullPointerException("请先初始化BaseConfig");
return sequencesUnusedDao;
}
public void setSequencesUnusedDao(SequencesUnusedDao sequencesUnusedDao) {
this.sequencesUnusedDao = sequencesUnusedDao;
}
public SequencesUnlockDao getSequencesUnlockDao() {
if (sequencesUnlockDao == null)
throw new NullPointerException("请先初始化BaseConfig");
return sequencesUnlockDao;
}
public void setSequencesUnlockDao(SequencesUnlockDao sequencesUnlockDao) {
this.sequencesUnlockDao = sequencesUnlockDao;
}
public Integer getStep() {
if (step == null)
throw new NullPointerException("请先初始化BaseConfig");
return step;
}
public void setStep(Integer step) {
this.step = step;
}
public String getType() {
if (type == null)
throw new NullPointerException("请先初始化BaseConfig");
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMinLength() {
if (minLength == null)
throw new NullPointerException("请先初始化BaseConfig");
return minLength;
}
public void setMinLength(Integer minLength) {
this.minLength = minLength;
}
private void init(GeneratorConfig generatorConfig) {
//数据库操作模板
JdbcTemplate jdbcTemplate = generatorConfig.getJdbcTemplate();
if (jdbcTemplate == null) {
//数据源
DataSource dataSource = generatorConfig.getDataSource();
if (dataSource == null)
//若数据库操作模板为空,也没有配置数据源,则抛出异常
throw new NullPointerException("数据源不能为空");
//否则以数据源创建数据库操作模板
jdbcTemplate = new JdbcTemplate(dataSource);
}
if (generatorConfig.getTransactionTemplate() == null) {
//若没有配置事务操作模板,则从配置中取事务管理器
DataSourceTransactionManager transactionManager = generatorConfig.getTransactionManager();
if (transactionManager == null) {
//若未配置事务管理器,则通过数据源新建
DataSource dataSource = jdbcTemplate.getDataSource();
if (dataSource == null)
throw new NullPointerException("数据源不能为空");
transactionManager = new DataSourceTransactionManager(dataSource);
}
//通过事务管理器创建事务操作模板
transactionTemplate = new TransactionTemplate(transactionManager);
} else {
//获取事务操作模板
transactionTemplate = generatorConfig.getTransactionTemplate();
}
this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.step = generatorConfig.getStep();
this.type = generatorConfig.getType();
this.minLength = generatorConfig.getMinLength();
}
}

View File

@@ -1,4 +1,4 @@
package com.cdhncy.seq.config;
package com.yanghuanglin.seq.config;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@@ -43,6 +43,16 @@ public class GeneratorConfig {
*/
private Integer step = 1;
/**
* 格式化后序号字符串的最小长度不足的部分补零
*/
private Integer minLength = 1;
/**
* 默认序号类型
*/
private String type="DEFAULT";
/**
* 表和字段配置
*/
@@ -95,6 +105,22 @@ public class GeneratorConfig {
this.autoCreate = autoCreate;
}
public Integer getMinLength() {
return minLength;
}
public void setMinLength(Integer minLength) {
this.minLength = minLength;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getStep() {
return step;
}

View File

@@ -1,4 +1,4 @@
package com.cdhncy.seq.config;
package com.yanghuanglin.seq.config;
/**
* 生成器对应的数据库表和字段配置

View File

@@ -1,6 +1,6 @@
package com.cdhncy.seq.dao;
package com.yanghuanglin.seq.dao;
import com.cdhncy.seq.po.Sequences;
import com.yanghuanglin.seq.po.Sequences;
/**
* @author yanghuanglin

View File

@@ -1,6 +1,6 @@
package com.cdhncy.seq.dao;
package com.yanghuanglin.seq.dao;
import com.cdhncy.seq.po.SequencesUnlock;
import com.yanghuanglin.seq.po.SequencesUnlock;
import java.util.Date;
import java.util.List;

View File

@@ -1,7 +1,8 @@
package com.cdhncy.seq.dao;
package com.yanghuanglin.seq.dao;
import com.cdhncy.seq.po.SequencesUnused;
import com.yanghuanglin.seq.po.SequencesUnused;
import java.util.Date;
import java.util.List;
/**
@@ -25,10 +26,25 @@ public interface SequencesUnusedDao {
*/
boolean delete(SequencesUnused sequencesUnused);
/**
* 保存空闲序号
*/
boolean save(SequencesUnused sequencesUnused);
/**
* 批量保存空闲序号
*/
boolean saveBatch(List<SequencesUnused> sequencesUnusedList);
void createTable();
/**
* 删除所有闲置的序号
*/
boolean deleteAll();
/**
* 删除指定时间段内使用中的序号
*/
boolean deleteByDate(Date begin, Date end);
}

View File

@@ -1,8 +1,8 @@
package com.cdhncy.seq.dao.impl;
package com.yanghuanglin.seq.dao.impl;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.dao.SequencesDao;
import com.cdhncy.seq.po.Sequences;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesDao;
import com.yanghuanglin.seq.po.Sequences;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -11,6 +11,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesDaoImpl implements SequencesDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@@ -56,9 +57,9 @@ public class SequencesDaoImpl implements SequencesDao {
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s` ( " +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 2 ) NOT NULL COMMENT '已使用到的序号'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '已使用到的序号'," +
" PRIMARY KEY ( `%s`, `%s` ) " +
" ) COMMENT '当前序号表'";
sql = String.format(sql, tableConfig.getTable(),

View File

@@ -1,8 +1,8 @@
package com.cdhncy.seq.dao.impl;
package com.yanghuanglin.seq.dao.impl;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.dao.SequencesUnlockDao;
import com.cdhncy.seq.po.SequencesUnlock;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnlockDao;
import com.yanghuanglin.seq.po.SequencesUnlock;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
@@ -13,6 +13,7 @@ import java.util.List;
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@@ -47,9 +48,22 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
@Override
public List<SequencesUnlock> listByDate(Date begin, Date end) {
String sql = "select * from `%s_unlock` where `%s`>=? and `%s`<=?";
String sql;
if (begin != null && end != null) {
sql = "select * from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), begin, end);
} else if (begin != null) {
sql = "select * from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), begin);
} else if (end != null) {
sql = "select * from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), end);
} else {
return listAll();
}
}
@Override
@@ -62,18 +76,30 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
@Override
public boolean deleteByDate(Date begin, Date end) {
String sql = "delete from `%s_unlock` where `%s`>=? and `%s`<=?";
String sql;
if (begin != null && end != null) {
sql = "delete from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
int result = this.jdbcTemplate.update(sql, begin, end);
return result != 0;
return this.jdbcTemplate.update(sql, begin, end) != 0;
} else if (begin != null) {
sql = "delete from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin) != 0;
} else if (end != null) {
sql = "delete from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0;
} else {
return deleteAll();
}
}
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_unlock` ( " +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 2 ) NOT NULL COMMENT '尚未锁定的序号'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '尚未锁定的序号'," +
" `%s` DATETIME NOT NULL COMMENT '使用时间'," +
" PRIMARY KEY ( `%s`, `%s` ,`%s` ) " +
" ) COMMENT '未锁定序号表'";

View File

@@ -1,8 +1,8 @@
package com.cdhncy.seq.dao.impl;
package com.yanghuanglin.seq.dao.impl;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.dao.SequencesUnusedDao;
import com.cdhncy.seq.po.SequencesUnused;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.po.SequencesUnused;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -10,12 +10,15 @@ import org.springframework.jdbc.core.RowMapper;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
/**
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@@ -27,7 +30,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override
public SequencesUnused findMinSeq(SequencesUnused sequencesUnused) {
String sql = "select * from `%s_ununsed` where `%s`=? and `%s`=? order by `%s` asc limit 0,1";
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? order by `%s` asc limit 0,1";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
try {
return this.jdbcTemplate.queryForObject(sql, rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
@@ -39,7 +42,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override
public SequencesUnused findMaxSeq(SequencesUnused sequencesUnused) {
try {
String sql = "select * from `%s_ununsed` where `%s`=? and `%s`=? order by `%s` desc limit 0,1";
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? order by `%s` desc limit 0,1";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
return this.jdbcTemplate.queryForObject(sql, rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
} catch (EmptyResultDataAccessException ignored) {
@@ -49,16 +52,24 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override
public boolean delete(SequencesUnused sequencesUnused) {
String sql = "delete from `%s_ununsed` where `%s`=? and `%s`=? and `%s`=?";
String sql = "delete from `%s_unused` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq());
return result != 0;
}
@Override
public boolean save(SequencesUnused sequencesUnused) {
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn(), tableConfig.getCreateTimeColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq(), sequencesUnused.getCreateTime());
return result != 0;
}
@Override
public boolean saveBatch(List<SequencesUnused> sequencesUnusedList) {
String sql = "insert into `%s_ununsed`(`%s`,`%s`,`%s`) values(?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn(), tableConfig.getCreateTimeColumn());
int[] result = this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
@@ -66,6 +77,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
ps.setString(1, sequencesUnused.getKey());
ps.setString(2, sequencesUnused.getType());
ps.setLong(3, sequencesUnused.getSeq());
ps.setTimestamp(4, new Timestamp(sequencesUnused.getCreateTime().getTime()));
}
@Override
@@ -78,29 +90,60 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_ununsed` ( " +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 255 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 2 ) NOT NULL COMMENT '闲置的的序号'," +
String sql = "CREATE TABLE IF NOT EXISTS `%s_unused` ( " +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '闲置的的序号'," +
" `%s` DATETIME NOT NULL COMMENT '设为闲置序号的时间'," +
" PRIMARY KEY ( `%s`, `%s`, `%s` ) " +
" ) COMMENT '闲置序号表'";
sql = String.format(sql, tableConfig.getTable(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn(),
tableConfig.getCreateTimeColumn(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn());
this.jdbcTemplate.execute(sql);
}
@Override
public boolean deleteAll() {
String sql = "delete from `%s_unused`";
sql = String.format(sql, tableConfig.getTable());
int result = this.jdbcTemplate.update(sql);
return result != 0;
}
@Override
public boolean deleteByDate(Date begin, Date end) {
String sql;
if (begin != null && end != null) {
sql = "delete from `%s_unused` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin, end) != 0;
} else if (begin != null) {
sql = "delete from `%s_unused` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin) != 0;
} else if (end != null) {
sql = "delete from `%s_unused` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0;
} else {
return deleteAll();
}
}
private RowMapper<SequencesUnused> rowMapper() {
return (rs, rowNum) -> {
SequencesUnused result = new SequencesUnused();
result.setKey(rs.getString(tableConfig.getKeyColumn()));
result.setType(rs.getString(tableConfig.getTypeColumn()));
result.setSeq(rs.getLong(tableConfig.getSeqColumn()));
return result;
SequencesUnused sequencesUnused = new SequencesUnused();
sequencesUnused.setKey(rs.getString(tableConfig.getKeyColumn()));
sequencesUnused.setType(rs.getString(tableConfig.getTypeColumn()));
sequencesUnused.setSeq(rs.getLong(tableConfig.getSeqColumn()));
sequencesUnused.setCreateTime(rs.getDate(tableConfig.getCreateTimeColumn()));
return sequencesUnused;
};
}
}

View File

@@ -0,0 +1,62 @@
package com.yanghuanglin.seq.enums;
/**
* 格式占位符枚举
*
* @author yanghuanglin
* @since 2022/2/14
*/
public enum FormatPlaceholder {
/**
* 序号格式字符中的年
*/
YEAR("#year#"),
/**
* 序号格式字符中的月
*/
MONTH("#month#"),
/**
* 序号格式字符中的日
*/
DAY("#day#"),
/**
* 序号格式字符中的格式化后的序号
*/
SEQ("#seq#");
/**
* 调用toString()后的字符串,这个字符串用于正则匹配(替换格式字符串中的对应占位符)和反向查找(将占位符字符串转换为对应枚举)
*/
private final String placeholder;
/**
* 构造函数
*
* @param placeholder 格式占位符
*/
FormatPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public String getPlaceholder() {
return placeholder;
}
/**
* 将格式占位符转为对应枚举
*
* @param placeholder 格式占位符
* @return 对应枚举
*/
public static FormatPlaceholder of(String placeholder) {
FormatPlaceholder[] enumConstants = FormatPlaceholder.class.getEnumConstants();
for (FormatPlaceholder enumConstant : enumConstants) {
if (enumConstant.getPlaceholder().equals(placeholder))
return enumConstant;
}
return null;
}
}

View File

@@ -0,0 +1,231 @@
package com.yanghuanglin.seq.generator;
import com.yanghuanglin.seq.config.BaseConfig;
import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.enums.FormatPlaceholder;
import com.yanghuanglin.seq.po.Sequences;
import com.yanghuanglin.seq.po.SequencesUnlock;
import com.yanghuanglin.seq.po.SequencesUnused;
import java.util.Date;
public interface Generator {
/**
* 根据传入的key和type生成可用的序号对象。
* <p/>
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找不到记录说明该组合的序号对象还未初次生成返回的是seq为step的序号对象该对象数据会写入到{@link SequencesUnlock}中。
* <p/>
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @return 可用的序号对象
*/
Sequences generate(String key);
/**
* 根据传入的key和type生成可用的序号对象。
* <p/>
* 如果根据key和type在{@link Sequences}中找不到记录说明该组合的序号对象还未初次生成返回的是seq为step的序号对象该对象数据会写入到{@link SequencesUnlock}中。
* <p/>
* 如果根据key和type在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param type 序号类型
* @return 可用的序号对象
*/
Sequences generate(String key, String type);
/**
* 返回根据{@link #generate(String, String)}得到的序号对象,补零后的序号字符串
* <p/>
* 如生成的为3而minLength为5则返回的是00003
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @return 补零后的字符串
*/
String generate(String key, String type, Integer minLength);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Sequences sequences, String pattern);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param minLength 序号数字最小长度
* @param pattern 格式
* @return 格式化后的字符串
*/
String format(Sequences sequences, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR#getPlaceholder()}(当前年份)、{@link FormatPlaceholder#MONTH#getPlaceholder()}(当前月份)、{@link FormatPlaceholder#DAY#getPlaceholder()}(当前日期)、{@link FormatPlaceholder#SEQ#getPlaceholder()}(生成的字符串序号)四个变量
* <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param pattern 格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param minLength 序号最小长度,不足的会补零
* @param pattern 格式
* @return 格式化后的序号字符串
*/
String format(Long seq, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, Integer minLength, String pattern);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
* 注意:序号格式和格式化后的字符串占位一定要匹配。如:处〔#year##month#10801第#seq#号 对应 处20220210801第10001号而不能对应 处2022021110801第10001号
*
* @param formatted 格式化后的序号字符串
* @param pattern 序号格式
* @return 包含了序号字符串对应年如果有、月如果有、日如果有、序号的序号对象其key需要根据情况手动设置type为{@link GeneratorConfig#getType()}的默认值
*/
Sequences parse(String formatted, String pattern);
/**
* 锁定指定序号,在序号生成后,调用该序号的逻辑完成后需要执行此方法
* <p/>
* 如办理案件时,先调用{@link #generate(String, String)}或者{@link #generate(String, String, Integer)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* <p/>
* 注意,此处的锁定非数据库中锁定,而是{@link SequencesUnused}和{@link SequencesUnlock}中均不存在key、type、seq相同的记录视为锁定。因此此处实际是把这两个表中的记录均删除了
*
* @param sequences 需要锁定的序号
* @return 锁定结果
*/
boolean lock(Sequences sequences);
/**
* 释放所有未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*/
void release();
/**
* 释放指定时间段内未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*
* @param begin 开始时间
* @param end 结束时间
*/
void release(Date begin, Date end);
/**
* 释放从开始时间开始,到现在时间之间未使用的序号。结束时间为方法执行时的时间
*
* @param begin 开始时间
*/
void releaseAfter(Date begin);
/**
* 释放结束时间以前的序号
*
* @param end 结束时间
*/
void releaseBefore(Date end);
/**
* 释放指定序号。一般用于业务对象删除后,对应序号需要回收使用时。
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
*/
void release(Sequences sequences);
/**
* 清空所有闲置序号和未锁定序号
*/
void clear();
/**
* 清空指定时间段内闲置序号和未锁定序号
*/
void clear(Date begin, Date end);
/**
* 清空从开始时间到限制时间之间闲置序号和未锁定序号,结束时间为方法执行时的时间
*
* @param begin 开始时间
*/
void clearAfter(Date begin);
/**
* 清空结束时间之前的限制序号和未锁定序号
*
* @param end 结束时间
*/
void clearBefore(Date end);
}

View File

@@ -0,0 +1,316 @@
package com.yanghuanglin.seq.generator.impl;
import com.yanghuanglin.seq.config.BaseConfig;
import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.dao.SequencesDao;
import com.yanghuanglin.seq.dao.SequencesUnlockDao;
import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.enums.FormatPlaceholder;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.po.Sequences;
import com.yanghuanglin.seq.po.SequencesUnlock;
import com.yanghuanglin.seq.po.SequencesUnused;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.yanghuanglin.seq.enums.FormatPlaceholder.*;
public class SequencesGenerator implements Generator {
private final TransactionTemplate transactionTemplate;
private final SequencesDao sequencesDao;
private final SequencesUnusedDao sequencesUnusedDao;
private final SequencesUnlockDao sequencesUnlockDao;
private final Integer step;
private final String type;
private final Integer minLength;
public SequencesGenerator(GeneratorConfig generatorConfig) {
BaseConfig baseConfig = BaseConfig.getInstance(generatorConfig);
this.transactionTemplate = baseConfig.getTransactionTemplate();
this.sequencesDao = baseConfig.getSequencesDao();
this.sequencesUnusedDao = baseConfig.getSequencesUnusedDao();
this.sequencesUnlockDao = baseConfig.getSequencesUnlockDao();
this.step = baseConfig.getStep();
this.type = baseConfig.getType();
this.minLength = baseConfig.getMinLength();
createTable(generatorConfig.getAutoCreate());
}
/**
* 创建需要的表
*
* @param autoCreate 是否自动创建
*/
private synchronized void createTable(Boolean autoCreate) {
if (!autoCreate)
return;
this.sequencesDao.createTable();
this.sequencesUnusedDao.createTable();
this.sequencesUnlockDao.createTable();
}
@Override
public synchronized Sequences generate(String key) {
return generate(key, type);
}
@Override
public synchronized Sequences generate(String key, String type) {
return transactionTemplate.execute(status -> {
try {
//根据传入的key和type新生成查询条件对象
Sequences condition = new Sequences(key, type);
//找到正在使用的最大序号
Sequences sequences = sequencesDao.find(condition);
if (sequences == null) {
//不存在说明还没生成将新生成的入库此时序号为默认的0
sequences = condition;
sequencesDao.save(sequences);
}
//根据传入的key和type查找空闲编号最小的一个
SequencesUnused conditionIdle = new SequencesUnused(condition);
SequencesUnused sequencesUnused = sequencesUnusedDao.findMinSeq(conditionIdle);
if (sequencesUnused == null) {
//空闲编号不存在,说明是未生成过,序号需要增加后直接使用,同时将新生成的写入到使用中表
sequences.increase(step);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequences);
sequencesUnlock.setCreateTime(new Date());
sequencesDao.update(sequences);
sequencesUnlockDao.save(sequencesUnlock);
} else {
//空闲编号存在,说明已经生成过,序号不需要增加,直接使用。同时将该空闲编号移动到使用中表
sequences = new Sequences(sequencesUnused);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequencesUnused);
sequencesUnlock.setCreateTime(new Date());
sequencesUnlockDao.save(sequencesUnlock);
sequencesUnusedDao.delete(sequencesUnused);
}
return sequences;
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return null;
}
});
}
@Override
public synchronized String generate(String key, String type, Integer minLength) {
Sequences sequences = this.generate(key, type);
if (sequences == null)
return null;
return sequences.format(minLength);
}
@Override
public String format(Sequences sequences, String pattern) {
return format(sequences, minLength, pattern);
}
@Override
public String format(Sequences sequences, Integer minLength, String pattern) {
return format(sequences.getSeq(), minLength, pattern);
}
@Override
public String format(Long seq, String pattern) {
return format(seq, minLength, pattern);
}
@Override
public String format(Long seq, Integer minLength, String pattern) {
return format(seq, null, minLength, pattern);
}
@Override
public String format(Long seq, String start, String pattern) {
return format(seq, start, minLength, pattern);
}
@Override
public String format(Long seq, String start, Integer minLength, String pattern) {
if (start == null)
start = "";
String seqString = start + new Sequences(seq).format(minLength);
Calendar calendar = Calendar.getInstance();
pattern = pattern.replaceAll(YEAR.getPlaceholder(), String.valueOf(calendar.get(Calendar.YEAR)));
pattern = pattern.replaceAll(MONTH.getPlaceholder(), String.format("%02d", calendar.get(Calendar.MONTH) + 1));
pattern = pattern.replaceAll(DAY.getPlaceholder(), String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
pattern = pattern.replaceAll(SEQ.getPlaceholder(), seqString);
return pattern;
}
@Override
public Sequences parse(String formatted, String pattern) {
//年、月、日、序号分隔特殊符号正则规则
String splitRegString = "(" + YEAR.getPlaceholder() + "|" + MONTH.getPlaceholder() + "|" + DAY.getPlaceholder() + "|" + SEQ.getPlaceholder() + ")";
//根据年、月、日、序号的特殊符号,对格式进行分隔,得到排除特殊符号后的字符串数组
String[] split = pattern.split(splitRegString);
for (String splitString : split) {
//用排除特殊符号后的字符串依次替换序号格式字符串和格式化后的序号字符串,得到纯净的序号字符串和序号格式对应关系
pattern = pattern.replace(splitString, "");
formatted = formatted.replace(splitString, "");
}
//年、月、日的数字匹配正则规则
String yearRegStr = "\\d{4}";
String monthRegStr = "\\d{2}";
String dayRegStr = "\\d{2}";
//将序号格式分隔特殊符号字符串转为正则匹配规则
Pattern seqPattern = Pattern.compile(splitRegString);
//对序号格式进行匹配
Matcher matcher = seqPattern.matcher(pattern);
//将年、月、日匹配规则字符串转为正则匹配规则
Pattern yearPattern = Pattern.compile(yearRegStr);
Pattern monthPattern = Pattern.compile(monthRegStr);
Pattern dayPattern = Pattern.compile(dayRegStr);
//默认的年、月、日均为空字符串
String year = "", month = "", day = "", seq = "";
//根据序号匹配规则字符串查找字符串分组
while (matcher.find()) {
String group = matcher.group();
FormatPlaceholder formatPlaceholder = of(group);
if (formatPlaceholder == null)
continue;
switch (formatPlaceholder) {
case YEAR:
//若分组为年份分组则将年份正则匹配到的字符串赋值给year同时把格式化后的序号字符串中对应年的字符串替换为空字符串
Matcher yearMatcher = yearPattern.matcher(formatted);
if (yearMatcher.find()) {
year = yearMatcher.group();
}
formatted = formatted.replaceFirst(yearRegStr, "");
break;
case MONTH:
//若分组为月份分组则将月份正则匹配到的字符串赋值给month同时把格式化后的序号字符串中对应月的字符串替换为空字符串
Matcher monthMatcher = monthPattern.matcher(formatted);
if (monthMatcher.find()) {
month = monthMatcher.group();
}
formatted = formatted.replaceFirst(monthRegStr, "");
break;
case DAY:
//若分组为日期分组则将日期正则匹配到的字符串赋值给day同时把格式化后的序号字符串中对应日期的字符串替换为空字符串
Matcher dayMatcher = dayPattern.matcher(formatted);
if (dayMatcher.find()) {
day = dayMatcher.group();
}
formatted = formatted.replaceFirst(dayRegStr, "");
break;
}
}
//经过以上替换后最后剩下的为序号这个序号可能是补零了的需要调用Long.parseLong来去零
seq = formatted;
//构建一个新的序号对象
Sequences sequences = new Sequences();
//用获取到的年、月、日、序号给新构建的序号对象设置对应的值
sequences.setYear(StringUtils.hasLength(year) ? Integer.valueOf(year) : null);
sequences.setMonth(StringUtils.hasLength(month) ? Integer.valueOf(month) : null);
sequences.setDay(StringUtils.hasLength(day) ? Integer.valueOf(day) : null);
sequences.setSeq(StringUtils.hasLength(seq) ? Long.parseLong(seq) : 0L);
sequences.setType(type);
return sequences;
}
@Override
public synchronized boolean lock(Sequences sequences) {
if (sequences == null)
return true;
SequencesUnlock condition = new SequencesUnlock(sequences);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
return sequencesUnlockDao.delete(condition);
}
@Override
public synchronized void release() {
//列出所有使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listAll();
List<SequencesUnused> sequencesUnusedList = new ArrayList<>();
for (SequencesUnlock sequencesUnlock : sequencesUnlockList) {
sequencesUnusedList.add(new SequencesUnused(sequencesUnlock, new Date()));
}
//将使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除所有使用中表的数据
sequencesUnlockDao.deleteAll();
}
@Override
public synchronized void release(Date begin, Date end) {
//列出指定时间段内使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listByDate(begin, end);
List<SequencesUnused> sequencesUnusedList = new ArrayList<>();
for (SequencesUnlock sequencesUnlock : sequencesUnlockList) {
sequencesUnusedList.add(new SequencesUnused(sequencesUnlock, new Date()));
}
//将指定时间段内使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除指定时间段内使用中表的数据
sequencesUnlockDao.deleteByDate(begin, end);
}
@Override
public synchronized void releaseAfter(Date begin) {
release(begin, null);
}
@Override
public synchronized void releaseBefore(Date end) {
release(null, end);
}
@Override
public synchronized void release(Sequences sequences) {
if (sequences == null)
return;
sequencesUnlockDao.delete(new SequencesUnlock(sequences));
sequencesUnusedDao.save(new SequencesUnused(sequences, new Date()));
}
@Override
public synchronized void clear() {
sequencesUnlockDao.deleteAll();
sequencesUnusedDao.deleteAll();
}
@Override
public synchronized void clear(Date begin, Date end) {
sequencesUnlockDao.deleteByDate(begin, end);
sequencesUnusedDao.deleteByDate(begin, end);
}
@Override
public synchronized void clearAfter(Date begin) {
clear(begin, null);
}
@Override
public synchronized void clearBefore(Date end) {
clear(null, end);
}
}

View File

@@ -0,0 +1,161 @@
package com.yanghuanglin.seq.po;
import com.yanghuanglin.seq.config.BaseConfig;
/**
* 当前序号
*
* @author yanghuanglin
* @since 2022/1/28
*/
public class Sequences {
/**
* 需要生成序号的key和type组成唯一主键
*/
protected String key;
/**
* 需要生成序号的类型和key组成唯一主键
*/
protected String type;
/**
* 默认序号
*/
protected Long seq = 0L;
/**
* 临时字段序号对应的年份如2022年如果能获取到的话
* 该字段仅用于解析序号字符串时解析出对应年份用于合成key序号对应的key为SNT+年份,返回的为其年份)
*/
private transient Integer year;
/**
* 临时字段序号对应的月份如2月如果能获取到的话
* 该字段仅用于解析序号字符串时解析出对应月份用于合成key序号对应的key为SNT+年份+月份,返回的为其月份)
*/
private transient Integer month;
/**
* 临时字段序号对应的日期如1日如果能获取到的话
* 该字段仅用于解析序号字符串时解析出对应日期用于合成key序号对应的key为SNT+年份+月份+日期,返回的为其日期)
*/
private transient Integer day;
public Sequences() {
}
public Sequences(Long seq) {
this.seq = seq;
}
public Sequences(String key, String type) {
this.key = key;
this.type = type;
}
public Sequences(String key, String type, Long seq) {
this.key = key;
this.type = type;
this.seq = seq;
}
public Sequences(SequencesUnused sequencesUnused) {
this.key = sequencesUnused.getKey();
this.type = sequencesUnused.getType();
this.seq = sequencesUnused.getSeq();
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSeq() {
return seq;
}
public void setSeq(Long seq) {
this.seq = seq;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getMonth() {
return month;
}
public void setMonth(Integer month) {
this.month = month;
}
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
/**
* 将序号增加指定步长
*
* @param step 步长
*/
public void increase(Integer step) {
this.seq += step;
}
/**
* 序号补零
*
* @return 补零后的序号,若未单独设置序号的长度,则最小长度为{@link BaseConfig#getMinLength()}长度;否则为修改后的长度,不足部分补零
*/
public String format() {
Integer minLength = BaseConfig.getInstance().getMinLength();
if (minLength != null)
return String.format("%0" + minLength + "d", this.seq);
return String.valueOf(this.seq);
}
/**
* 序号补零
*
* @param minLength 最小长度,低于此长度,会补零
* @return 补零后的序号
*/
public String format(Integer minLength) {
if (minLength != null)
return String.format("%0" + minLength + "d", this.seq);
return String.valueOf(this.seq);
}
@Override
public String toString() {
return "Sequences{" +
"key='" + key + '\'' +
", type='" + type + '\'' +
", seq=" + seq +
", year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}

View File

@@ -1,4 +1,4 @@
package com.cdhncy.seq.po;
package com.yanghuanglin.seq.po;
import java.util.Date;
@@ -34,4 +34,14 @@ public class SequencesUnlock extends Sequences {
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "SequencesUnlock{" +
"key='" + key + '\'' +
", type='" + type + '\'' +
", seq=" + seq +
", createTime=" + createTime +
'}';
}
}

View File

@@ -0,0 +1,48 @@
package com.yanghuanglin.seq.po;
import java.util.Date;
/**
* 闲置序号
*
* @author yanghuanglin
* @since 2022/1/28
*/
public class SequencesUnused extends Sequences {
private Date createTime;
public SequencesUnused() {
}
public SequencesUnused(Sequences sequences) {
this.key = sequences.getKey();
this.type = sequences.getType();
this.seq = sequences.getSeq();
}
public SequencesUnused(Sequences sequences, Date createTime) {
this.key = sequences.getKey();
this.type = sequences.getType();
this.seq = sequences.getSeq();
this.createTime = createTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "SequencesUnused{" +
"key='" + key + '\'' +
", type='" + type + '\'' +
", seq=" + seq +
", createTime=" + createTime +
'}';
}
}

View File

@@ -1,9 +1,9 @@
import com.cdhncy.seq.config.GeneratorConfig;
import com.cdhncy.seq.config.TableConfig;
import com.cdhncy.seq.po.Sequences;
import com.cdhncy.seq.generator.Generator;
import com.cdhncy.seq.generator.impl.SequencesGenerator;
import com.mysql.cj.jdbc.MysqlDataSource;
import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import com.yanghuanglin.seq.po.Sequences;
import org.junit.Test;
import java.util.HashSet;
@@ -27,10 +27,10 @@ public class SeqTest {
GeneratorConfig generatorConfig = new GeneratorConfig(dataSource);
TableConfig tableConfig = new TableConfig();
// tableConfig.setTable("sequences");
// tableConfig.setKeyColumn("SEQUENCE_KEY");
// tableConfig.setTypeColumn("SEQUENCE_TYPE");
// tableConfig.setSeqColumn("SEQUENCE_NEXT_ID");
tableConfig.setTable("sequences");
tableConfig.setKeyColumn("SEQUENCE_KEY");
tableConfig.setTypeColumn("SEQUENCE_TYPE");
tableConfig.setSeqColumn("CURRENT");
generatorConfig.setTableConfig(tableConfig);
generator = new SequencesGenerator(generatorConfig);
@@ -47,7 +47,7 @@ public class SeqTest {
int finalI = i;
threadPoolExecutor.execute(() -> {
Sequences sequences = generator.generate("SNT", "MISSION");
String formattedSeq = generator.format(sequences.getSeq(), 5, "处〔#year#10801#seq#");
String formattedSeq = generator.format(sequences.getSeq(), "处〔#year#10801#seq#");
// if (finalI % 2 == 0)
// System.out.println(3 / 0);
generator.lock(sequences);
@@ -73,4 +73,18 @@ public class SeqTest {
String s = "select * from sequences where `%s`=? and `%s`=?";
System.out.println(String.format(s, "key", "value"));
}
@Test
public void parseTest() {
String seqPattern = "ZZF#year##month##seq#";
String formatted = "ZZF20220200008";
Sequences sequences = generator.parse(formatted, seqPattern);
String key = "zzfCode" + sequences.getYear();
sequences.setKey(key);
sequences.setType("MISSION");
System.out.println(sequences);
}
}