Flicker方案用于生成自增ID
主要思路采用了MySQL自增长ID的机制(auto_increment + replace into)
建表语句:
CREATE TABLE `tb_seqno` (
`a` varchar(1) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_a` (`a`)
) ENGINE=MyISAM AUTO_INCREMENT=25 DEFAULT CHARSET=utf8
【Flicker方案用于生成自增ID】代码实现:
/**
* Created by huoshaofeng on 2018/5/29.
* 生成交易流水号:6位日期+10位源应用号+9位自增整数
*///@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "/applicationContext.xml")
@Service
@Slf4j
public class GenSeqNoUtil {@Qualifier("jade.dataSource.com.XXXXXX.YYYY.ZZZZ.dao")
@Autowired
org.apache.commons.dbcp.BasicDataSource dataSource;
String SQL_REPLACE = "REPLACE INTO tb_seqNo(`a`) VALUE('a')";
//@Transactional(propagation = Propagation.REQUIRES_NEW)
public String genSeqNo(){Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
String currentDateStr = sdf.format(currentDate);
String sourceAppId = BaixinTradeConstants.KEY_SOURCE_APP_ID;
Long autoNumber = getSerialId(SQL_REPLACE) % 1000000000L;
String autoNumberStr = String.format("%09d", autoNumber);
//System.out.println(currentDateStr + sourceAppId + autoNumberStr);
return currentDateStr + sourceAppId + autoNumberStr;
}private long getSerialId(String genSql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
stmt = conn.createStatement();
stmt.execute(genSql);
rs = stmt.executeQuery("select last_insert_id()");
rs.next();
long id = rs.getLong(1);
return id;
} catch (Throwable t) {
log.error("fail to get serial id", t);
} finally {
try {
if(rs != null) {
rs.close();
}
if(stmt != null) {
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
log.error("fail to close db connection resource", e);
}
}
return -1;
}
}
推荐阅读
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- 定制一套英文学习方案
- 托福听力高分备考方案
- 私有化轻量级持续集成部署方案--03-部署web服务(下)
- Spark|Spark 数据倾斜及其解决方案
- [丰声]简字·第14期|[丰声]简字·第14期 精要主义(有限时间精力只用于有意义的事)
- #12-UITableView|#12-UITableView 优化方案
- 小版隧道镜子解决方案
- stm32|基于STM32和freeRTOS智能门锁设计方案
- 适用于小白(VSCode搭建Vue项目,最详细的搭建步骤哦)