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

代码实现:


/**
 * 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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值