我是靠谱客的博主 自然台灯,这篇文章主要介绍在系统中生成业务ID的几种方法,现在分享给大家,希望可以做个参考。

在系统中,除了使用数据库表本身的Id,如何生成各种业务Id?一下记录几种生成Id的方式:

  1. 使用数据库表记录生成的Id,以MySQL为例:

1) 首先创建一个数据库表,来记录当前的业务Id

复制代码
1
2
3
4
5
6
7
8
CREATE TABLE `global_auto_number` ( `id` varchar(32) NOT NULL, `version_optimized_lock` int(11) NOT NULL, `business_key` varchar(255) NOT NULL COMMENT 'Can use full business class name as business key', `current_num` bigint(22) NOT NULL COMMENT 'current number', PRIMARY KEY (`id`), UNIQUE KEY `UK_AUTO_NUMBER` (`business_key`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

 2) 获取Id的方法:

复制代码
1
2
3
4
5
6
int currentCount = jdbcTemplate.update("update global_auto_number set current_num = LAST_INSERT_ID(current_num + 1) where business_key = ?", new Object[] {businessKey}); if(currentCount == 0) { jdbcTemplate.update("insert into global_auto_number (id, version_optimized_lock, business_key, current_num) values (?, 1, ?, 0)", new Object[] {UUIDGenerator.generateUUID(),businessKey}); jdbcTemplate.update("update global_auto_number set current_num = LAST_INSERT_ID(current_num + 1) where business_key = ?", new Object[] {businessKey}); } return jdbcTemplate.queryForLong("select LAST_INSERT_ID()");

 3) 按照业务逻辑格式化获取的Id。例如:

复制代码
1
String.format("SEQ%09d", 123)

 4) 注意事务需要用REQUIRES_NEW,否则在并发环境下会出现大量乐观锁问题。

 

2. 使用随机数来生成随机的Id,例如使用同一个Id来追踪后台响应用户操作的各种log

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static String generateRandomId() { byte[] bytes = new byte[10]; try { SecureRandom.getInstance("SHA1PRNG").nextBytes(bytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return toHexString(bytes); } final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String toHexString(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); }

 

 

 

 

 

 

 

最后

以上就是自然台灯最近收集整理的关于在系统中生成业务ID的几种方法的全部内容,更多相关在系统中生成业务ID内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(91)

评论列表共有 0 条评论

立即
投稿
返回
顶部