1. 电商分布式ID概述

电商分布式ID是在电商系统中用于唯一标识各种电商资源的标识符。电商系统对ID的要求非常严格,需要满足全局唯一、高性能、高可用、趋势递增、信息安全、业务隔离、秒杀支持、库存管理、订单追踪等特性。电商分布式ID不仅要保证技术层面的唯一性,还要满足电商业务需求,支持高并发场景,防范超卖问题。本文将详细介绍电商级分布式ID生成方案的原理、实现细节以及在Java企业级电商应用中的最佳实践。

1.1 电商分布式ID核心价值

  1. 全局唯一性: 在整个电商系统中保证ID的唯一性
  2. 高性能: 支持高并发电商交易场景下的ID生成
  3. 高可用性: 电商系统故障时仍能正常生成ID
  4. 趋势递增: ID具有时间顺序性,便于数据库索引和业务分析
  5. 信息安全: 避免暴露电商业务信息
  6. 业务隔离: 支持不同业务模块的ID隔离
  7. 秒杀支持: 支持高并发秒杀场景
  8. 库存管理: 支持库存管理和防超卖

1.2 电商分布式ID应用场景

  • 订单系统: 订单ID、支付ID、退款ID生成
  • 商品系统: 商品ID、SKU ID、分类ID生成
  • 用户系统: 用户ID、会员ID、积分ID生成
  • 库存系统: 库存ID、仓库ID、批次ID生成
  • 营销系统: 优惠券ID、活动ID、秒杀ID生成

1.3 电商分布式ID实现方案

  • 电商雪花算法: 增强版雪花算法,支持电商特性
  • 电商UUID: 电商级UUID生成器
  • 电商数据库自增: 基于数据库的电商级自增ID
  • 电商Redis: 基于Redis的电商级原子操作
  • 电商Zookeeper: 基于Zookeeper的电商级序列号
  • 电商Leaf: 电商级分布式ID生成器

2. 电商分布式ID基础实现

2.1 电商分布式ID配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* 电商分布式ID配置类
* @author Java实战
*/
@Configuration
@EnableConfigurationProperties(EcommerceDistributedIdProperties.class)
public class EcommerceDistributedIdConfig {

@Autowired
private EcommerceDistributedIdProperties properties;

/**
* 电商雪花算法ID生成器
* @return 电商雪花算法ID生成器
*/
@Bean
public EcommerceSnowflakeIdGenerator ecommerceSnowflakeIdGenerator() {
return new EcommerceSnowflakeIdGenerator(
properties.getSnowflake().getWorkerId(),
properties.getSnowflake().getDatacenterId(),
properties.getSnowflake().getEcommerceId()
);
}

/**
* 电商UUID生成器
* @return 电商UUID生成器
*/
@Bean
public EcommerceUuidGenerator ecommerceUuidGenerator() {
return new EcommerceUuidGenerator();
}

/**
* 电商数据库自增ID生成器
* @return 电商数据库自增ID生成器
*/
@Bean
public EcommerceDatabaseIdGenerator ecommerceDatabaseIdGenerator() {
return new EcommerceDatabaseIdGenerator();
}

/**
* 电商Redis ID生成器
* @return 电商Redis ID生成器
*/
@Bean
public EcommerceRedisIdGenerator ecommerceRedisIdGenerator() {
return new EcommerceRedisIdGenerator();
}

/**
* 电商Zookeeper ID生成器
* @return 电商Zookeeper ID生成器
*/
@Bean
public EcommerceZookeeperIdGenerator ecommerceZookeeperIdGenerator() {
return new EcommerceZookeeperIdGenerator();
}

/**
* 电商分布式ID服务
* @return 电商分布式ID服务
*/
@Bean
public EcommerceDistributedIdService ecommerceDistributedIdService() {
return new EcommerceDistributedIdService();
}

/**
* 电商分布式ID监控服务
* @return 电商分布式ID监控服务
*/
@Bean
public EcommerceDistributedIdMonitorService ecommerceDistributedIdMonitorService() {
return new EcommerceDistributedIdMonitorService();
}

/**
* 电商分布式ID业务服务
* @return 电商分布式ID业务服务
*/
@Bean
public EcommerceDistributedIdBusinessService ecommerceDistributedIdBusinessService() {
return new EcommerceDistributedIdBusinessService();
}

/**
* 电商分布式ID秒杀服务
* @return 电商分布式ID秒杀服务
*/
@Bean
public EcommerceDistributedIdSeckillService ecommerceDistributedIdSeckillService() {
return new EcommerceDistributedIdSeckillService();
}

private static final Logger logger = LoggerFactory.getLogger(EcommerceDistributedIdConfig.class);
}

2.2 电商分布式ID属性配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
* 电商分布式ID属性配置
* @author Java实战
*/
@Data
@ConfigurationProperties(prefix = "ecommerce-distributed-id")
public class EcommerceDistributedIdProperties {

/**
* 是否启用电商分布式ID
*/
private boolean enableEcommerceDistributedId = true;

/**
* 默认ID生成器类型
*/
private String defaultGeneratorType = "ECOMMERCE_SNOWFLAKE";

/**
* 电商雪花算法配置
*/
private EcommerceSnowflakeConfig snowflake = new EcommerceSnowflakeConfig();

/**
* 电商UUID配置
*/
private EcommerceUuidConfig uuid = new EcommerceUuidConfig();

/**
* 电商数据库自增配置
*/
private EcommerceDatabaseConfig database = new EcommerceDatabaseConfig();

/**
* 电商Redis配置
*/
private EcommerceRedisConfig redis = new EcommerceRedisConfig();

/**
* 电商Zookeeper配置
*/
private EcommerceZookeeperConfig zookeeper = new EcommerceZookeeperConfig();

/**
* 业务配置
*/
private BusinessConfig business = new BusinessConfig();

/**
* 秒杀配置
*/
private SeckillConfig seckill = new SeckillConfig();

/**
* 库存配置
*/
private InventoryConfig inventory = new InventoryConfig();

/**
* 是否启用监控
*/
private boolean enableMonitoring = true;

/**
* 监控间隔(毫秒)
*/
private long monitorInterval = 30000;

/**
* 是否启用告警
*/
private boolean enableAlert = true;

/**
* 生成失败率告警阈值
*/
private double failureRateAlertThreshold = 0.001;

/**
* 生成延迟告警阈值(毫秒)
*/
private long latencyAlertThreshold = 50;

/**
* 电商雪花算法配置类
*/
@Data
public static class EcommerceSnowflakeConfig {
/**
* 工作机器ID
*/
private long workerId = 1L;

/**
* 数据中心ID
*/
private long datacenterId = 1L;

/**
* 电商ID
*/
private long ecommerceId = 1L;

/**
* 起始时间戳
*/
private long startTimestamp = 1609459200000L; // 2021-01-01 00:00:00

/**
* 是否启用电商雪花算法
*/
private boolean enableSnowflake = true;

/**
* 序列号位数
*/
private long sequenceBits = 10L;

/**
* 机器标识位数
*/
private long workerIdBits = 5L;

/**
* 数据中心标识位数
*/
private long datacenterIdBits = 5L;

/**
* 电商标识位数
*/
private long ecommerceIdBits = 4L;

/**
* 时间戳位数
*/
private long timestampBits = 40L;

/**
* 是否启用加密
*/
private boolean enableEncryption = true;

/**
* 加密密钥
*/
private String encryptionKey = "ecommerce-distributed-id-key";
}

/**
* 电商UUID配置类
*/
@Data
public static class EcommerceUuidConfig {
/**
* UUID版本
*/
private String version = "UUID4";

/**
* 是否启用电商UUID
*/
private boolean enableUuid = false;

/**
* 是否使用连字符
*/
private boolean useHyphens = true;

/**
* 是否转大写
*/
private boolean useUpperCase = false;

/**
* 是否启用加密
*/
private boolean enableEncryption = true;

/**
* 加密密钥
*/
private String encryptionKey = "ecommerce-uuid-key";
}

/**
* 电商数据库自增配置类
*/
@Data
public static class EcommerceDatabaseConfig {
/**
* 数据源名称
*/
private String dataSourceName = "ecommerce";

/**
* 是否启用电商数据库自增
*/
private boolean enableDatabase = false;

/**
* 表名
*/
private String tableName = "ecommerce_id_generator";

/**
* 字段名
*/
private String fieldName = "id";

/**
* 步长
*/
private int step = 1;

/**
* 初始值
*/
private long initialValue = 1L;

/**
* 是否启用加密
*/
private boolean enableEncryption = true;

/**
* 加密密钥
*/
private String encryptionKey = "ecommerce-database-key";
}

/**
* 电商Redis配置类
*/
@Data
public static class EcommerceRedisConfig {
/**
* Redis键前缀
*/
private String keyPrefix = "ecommerce:distributed:id:";

/**
* 是否启用电商Redis
*/
private boolean enableRedis = false;

/**
* 过期时间(秒)
*/
private long expireTime = 3600;

/**
* 步长
*/
private int step = 1;

/**
* 初始值
*/
private long initialValue = 1L;

/**
* 是否启用加密
*/
private boolean enableEncryption = true;

/**
* 加密密钥
*/
private String encryptionKey = "ecommerce-redis-key";
}

/**
* 电商Zookeeper配置类
*/
@Data
public static class EcommerceZookeeperConfig {
/**
* Zookeeper连接地址
*/
private String connectString = "localhost:2181";

/**
* 是否启用电商Zookeeper
*/
private boolean enableZookeeper = false;

/**
* 会话超时时间(毫秒)
*/
private int sessionTimeout = 30000;

/**
* 连接超时时间(毫秒)
*/
private int connectionTimeout = 10000;

/**
* 根路径
*/
private String rootPath = "/ecommerce-distributed-id";

/**
* 是否启用加密
*/
private boolean enableEncryption = true;

/**
* 加密密钥
*/
private String encryptionKey = "ecommerce-zookeeper-key";
}

/**
* 业务配置类
*/
@Data
public static class BusinessConfig {
/**
* 是否启用业务隔离
*/
private boolean enableBusinessIsolation = true;

/**
* 业务类型映射
*/
private Map<String, String> businessTypeMapping = new HashMap<>();

/**
* 业务ID前缀
*/
private Map<String, String> businessIdPrefix = new HashMap<>();

/**
* 业务ID长度
*/
private Map<String, Integer> businessIdLength = new HashMap<>();
}

/**
* 秒杀配置类
*/
@Data
public static class SeckillConfig {
/**
* 是否启用秒杀
*/
private boolean enableSeckill = true;

/**
* 秒杀ID前缀
*/
private String seckillIdPrefix = "SK";

/**
* 秒杀ID长度
*/
private int seckillIdLength = 20;

/**
* 秒杀ID过期时间(秒)
*/
private long seckillIdExpireTime = 3600;

/**
* 秒杀并发限制
*/
private int seckillConcurrencyLimit = 10000;
}

/**
* 库存配置类
*/
@Data
public static class InventoryConfig {
/**
* 是否启用库存管理
*/
private boolean enableInventory = true;

/**
* 库存ID前缀
*/
private String inventoryIdPrefix = "INV";

/**
* 库存ID长度
*/
private int inventoryIdLength = 20;

/**
* 库存ID过期时间(秒)
*/
private long inventoryIdExpireTime = 3600;

/**
* 库存并发限制
*/
private int inventoryConcurrencyLimit = 10000;
}
}

2.3 电商分布式ID数据模型类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/**
* 电商分布式ID数据模型类
* @author Java实战
*/
@Data
@Table(name = "ecommerce_distributed_id_record")
public class EcommerceDistributedIdData {

/**
* 主键ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

/**
* 电商分布式ID
*/
@Column(name = "ecommerce_distributed_id", length = 64)
private String ecommerceDistributedId;

/**
* ID类型
*/
@Column(name = "id_type", length = 32)
private String idType;

/**
* 生成器类型
*/
@Column(name = "generator_type", length = 32)
private String generatorType;

/**
* 业务类型
*/
@Column(name = "business_type", length = 32)
private String businessType;

/**
* 电商业务类型
*/
@Column(name = "ecommerce_business_type", length = 32)
private String ecommerceBusinessType;

/**
* 生成时间
*/
@Column(name = "generate_time")
private LocalDateTime generateTime;

/**
* 过期时间
*/
@Column(name = "expire_time")
private LocalDateTime expireTime;

/**
* 状态
*/
@Column(name = "status", length = 20)
private String status;

/**
* 加密状态
*/
@Column(name = "encryption_status", length = 20)
private String encryptionStatus;

/**
* 业务状态
*/
@Column(name = "business_status", length = 20)
private String businessStatus;

/**
* 秒杀状态
*/
@Column(name = "seckill_status", length = 20)
private String seckillStatus;

/**
* 库存状态
*/
@Column(name = "inventory_status", length = 20)
private String inventoryStatus;

/**
* 扩展属性(JSON格式)
*/
@Column(name = "extended_properties", columnDefinition = "TEXT")
private String extendedProperties;

/**
* 业务信息(JSON格式)
*/
@Column(name = "business_info", columnDefinition = "TEXT")
private String businessInfo;

/**
* 秒杀信息(JSON格式)
*/
@Column(name = "seckill_info", columnDefinition = "TEXT")
private String seckillInfo;

/**
* 库存信息(JSON格式)
*/
@Column(name = "inventory_info", columnDefinition = "TEXT")
private String inventoryInfo;

/**
* 创建时间
*/
@Column(name = "create_time")
@CreationTimestamp
private LocalDateTime createTime;

/**
* 更新时间
*/
@Column(name = "update_time")
@UpdateTimestamp
private LocalDateTime updateTime;

public EcommerceDistributedIdData() {
this.status = "ACTIVE";
this.encryptionStatus = "ENCRYPTED";
this.businessStatus = "PENDING";
this.seckillStatus = "PENDING";
this.inventoryStatus = "PENDING";
this.generateTime = LocalDateTime.now();
}

public EcommerceDistributedIdData(String ecommerceDistributedId, String idType, String generatorType) {
this();
this.ecommerceDistributedId = ecommerceDistributedId;
this.idType = idType;
this.generatorType = generatorType;
}

/**
* 验证电商分布式ID数据
* @return 是否有效
*/
public boolean validate() {
if (ecommerceDistributedId == null || ecommerceDistributedId.isEmpty()) {
return false;
}

if (idType == null || idType.isEmpty()) {
return false;
}

if (generatorType == null || generatorType.isEmpty()) {
return false;
}

if (ecommerceBusinessType == null || ecommerceBusinessType.isEmpty()) {
return false;
}

return true;
}

/**
* 是否过期
* @return 是否过期
*/
public boolean isExpired() {
if (expireTime == null) {
return false;
}
return LocalDateTime.now().isAfter(expireTime);
}

/**
* 是否已加密
* @return 是否已加密
*/
public boolean isEncrypted() {
return "ENCRYPTED".equals(this.encryptionStatus);
}

/**
* 是否已业务处理
* @return 是否已业务处理
*/
public boolean isBusinessProcessed() {
return "BUSINESS_PROCESSED".equals(this.businessStatus);
}

/**
* 是否已秒杀处理
* @return 是否已秒杀处理
*/
public boolean isSeckillProcessed() {
return "SECKILL_PROCESSED".equals(this.seckillStatus);
}

/**
* 是否已库存处理
* @return 是否已库存处理
*/
public boolean isInventoryProcessed() {
return "INVENTORY_PROCESSED".equals(this.inventoryStatus);
}

/**
* 设置扩展属性
* @param key 键
* @param value 值
*/
public void setExtendedProperty(String key, Object value) {
Map<String, Object> properties = getExtendedPropertiesMap();
properties.put(key, value);
this.extendedProperties = JSON.toJSONString(properties);
}

/**
* 获取扩展属性
* @param key 键
* @return
*/
public Object getExtendedProperty(String key) {
Map<String, Object> properties = getExtendedPropertiesMap();
return properties.get(key);
}

/**
* 获取扩展属性Map
* @return 扩展属性Map
*/
private Map<String, Object> getExtendedPropertiesMap() {
if (extendedProperties == null || extendedProperties.isEmpty()) {
return new HashMap<>();
}
try {
return JSON.parseObject(extendedProperties, new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
return new HashMap<>();
}
}

/**
* 设置扩展属性Map
* @param properties 扩展属性Map
*/
public void setExtendedPropertiesMap(Map<String, Object> properties) {
this.extendedProperties = JSON.toJSONString(properties);
}

/**
* 设置业务信息
* @param businessInfo 业务信息
*/
public void setBusinessInfo(Map<String, Object> businessInfo) {
this.businessInfo = JSON.toJSONString(businessInfo);
}

/**
* 获取业务信息
* @return 业务信息
*/
public Map<String, Object> getBusinessInfo() {
if (businessInfo == null || businessInfo.isEmpty()) {
return new HashMap<>();
}
try {
return JSON.parseObject(businessInfo, new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
return new HashMap<>();
}
}

/**
* 设置秒杀信息
* @param seckillInfo 秒杀信息
*/
public void setSeckillInfo(Map<String, Object> seckillInfo) {
this.seckillInfo = JSON.toJSONString(seckillInfo);
}

/**
* 获取秒杀信息
* @return 秒杀信息
*/
public Map<String, Object> getSeckillInfo() {
if (seckillInfo == null || seckillInfo.isEmpty()) {
return new HashMap<>();
}
try {
return JSON.parseObject(seckillInfo, new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
return new HashMap<>();
}
}

/**
* 设置库存信息
* @param inventoryInfo 库存信息
*/
public void setInventoryInfo(Map<String, Object> inventoryInfo) {
this.inventoryInfo = JSON.toJSONString(inventoryInfo);
}

/**
* 获取库存信息
* @return 库存信息
*/
public Map<String, Object> getInventoryInfo() {
if (inventoryInfo == null || inventoryInfo.isEmpty()) {
return new HashMap<>();
}
try {
return JSON.parseObject(inventoryInfo, new TypeReference<Map<String, Object>>() {});
} catch (Exception e) {
return new HashMap<>();
}
}
}

/**
* 电商分布式ID生成结果类
* @author Java实战
*/
@Data
public class EcommerceDistributedIdResult {

/**
* 是否成功
*/
private boolean success;

/**
* 生成的ID
*/
private String id;

/**
* ID类型
*/
private String idType;

/**
* 生成器类型
*/
private String generatorType;

/**
* 业务类型
*/
private String businessType;

/**
* 电商业务类型
*/
private String ecommerceBusinessType;

/**
* 生成时间
*/
private LocalDateTime generateTime;

/**
* 错误信息
*/
private String error;

/**
* 开始时间
*/
private long startTime;

/**
* 结束时间
*/
private long endTime;

/**
* 重试次数
*/
private int retryCount;

/**
* 加密状态
*/
private String encryptionStatus;

/**
* 业务状态
*/
private String businessStatus;

/**
* 秒杀状态
*/
private String seckillStatus;

/**
* 库存状态
*/
private String inventoryStatus;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

/**
* 业务信息
*/
private Map<String, Object> businessInfo;

/**
* 秒杀信息
*/
private Map<String, Object> seckillInfo;

/**
* 库存信息
*/
private Map<String, Object> inventoryInfo;

public EcommerceDistributedIdResult() {
this.success = false;
this.retryCount = 0;
this.extendedProperties = new HashMap<>();
this.businessInfo = new HashMap<>();
this.seckillInfo = new HashMap<>();
this.inventoryInfo = new HashMap<>();
this.encryptionStatus = "ENCRYPTED";
this.businessStatus = "PENDING";
this.seckillStatus = "PENDING";
this.inventoryStatus = "PENDING";
}

public EcommerceDistributedIdResult(String id, String idType, String generatorType) {
this();
this.id = id;
this.idType = idType;
this.generatorType = generatorType;
this.generateTime = LocalDateTime.now();
}

/**
* 获取生成耗时
* @return 生成耗时(毫秒)
*/
public long getDuration() {
return endTime - startTime;
}

/**
* 是否成功
* @return 是否成功
*/
public boolean isSuccess() {
return success;
}

/**
* 增加重试次数
*/
public void incrementRetryCount() {
this.retryCount++;
}

/**
* 是否已加密
* @return 是否已加密
*/
public boolean isEncrypted() {
return "ENCRYPTED".equals(this.encryptionStatus);
}

/**
* 是否已业务处理
* @return 是否已业务处理
*/
public boolean isBusinessProcessed() {
return "BUSINESS_PROCESSED".equals(this.businessStatus);
}

/**
* 是否已秒杀处理
* @return 是否已秒杀处理
*/
public boolean isSeckillProcessed() {
return "SECKILL_PROCESSED".equals(this.seckillStatus);
}

/**
* 是否已库存处理
* @return 是否已库存处理
*/
public boolean isInventoryProcessed() {
return "INVENTORY_PROCESSED".equals(this.inventoryStatus);
}
}

/**
* 电商分布式ID状态信息类
* @author Java实战
*/
@Data
public class EcommerceDistributedIdStatus {

/**
* 总生成数
*/
private long totalGenerated;

/**
* 成功生成数
*/
private long successGenerated;

/**
* 失败生成数
*/
private long failureGenerated;

/**
* 重试生成数
*/
private long retryGenerated;

/**
* 加密生成数
*/
private long encryptedGenerated;

/**
* 业务处理数
*/
private long businessProcessed;

/**
* 秒杀处理数
*/
private long seckillProcessed;

/**
* 库存处理数
*/
private long inventoryProcessed;

/**
* 成功率
*/
private double successRate;

/**
* 失败率
*/
private double failureRate;

/**
* 重试率
*/
private double retryRate;

/**
* 加密率
*/
private double encryptionRate;

/**
* 业务处理率
*/
private double businessProcessRate;

/**
* 秒杀处理率
*/
private double seckillProcessRate;

/**
* 库存处理率
*/
private double inventoryProcessRate;

/**
* 平均生成时间(毫秒)
*/
private double averageGenerateTime;

/**
* 最大生成时间(毫秒)
*/
private long maxGenerateTime;

/**
* 最小生成时间(毫秒)
*/
private long minGenerateTime;

/**
* 最后检查时间
*/
private Long lastCheckTime;

/**
* 系统状态
*/
private String systemStatus;

/**
* 各生成器状态
*/
private Map<String, EcommerceGeneratorStatus> generatorStatuses;

public EcommerceDistributedIdStatus() {
this.lastCheckTime = System.currentTimeMillis();
this.systemStatus = "HEALTHY";
this.generatorStatuses = new HashMap<>();
}

/**
* 计算成功率
* @return 成功率
*/
public double calculateSuccessRate() {
if (totalGenerated > 0) {
return (double) successGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算失败率
* @return 失败率
*/
public double calculateFailureRate() {
if (totalGenerated > 0) {
return (double) failureGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算重试率
* @return 重试率
*/
public double calculateRetryRate() {
if (totalGenerated > 0) {
return (double) retryGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算加密率
* @return 加密率
*/
public double calculateEncryptionRate() {
if (totalGenerated > 0) {
return (double) encryptedGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算业务处理率
* @return 业务处理率
*/
public double calculateBusinessProcessRate() {
if (totalGenerated > 0) {
return (double) businessProcessed / totalGenerated;
}
return 0.0;
}

/**
* 计算秒杀处理率
* @return 秒杀处理率
*/
public double calculateSeckillProcessRate() {
if (totalGenerated > 0) {
return (double) seckillProcessed / totalGenerated;
}
return 0.0;
}

/**
* 计算库存处理率
* @return 库存处理率
*/
public double calculateInventoryProcessRate() {
if (totalGenerated > 0) {
return (double) inventoryProcessed / totalGenerated;
}
return 0.0;
}

/**
* 是否健康
* @return 是否健康
*/
public boolean isHealthy() {
return successRate >= 0.999 && failureRate <= 0.001 &&
encryptionRate >= 0.999 && businessProcessRate >= 0.999 &&
seckillProcessRate >= 0.999 && inventoryProcessRate >= 0.999;
}
}

/**
* 电商生成器状态类
* @author Java实战
*/
@Data
public class EcommerceGeneratorStatus {

/**
* 生成器类型
*/
private String generatorType;

/**
* 总生成数
*/
private long totalGenerated;

/**
* 成功生成数
*/
private long successGenerated;

/**
* 失败生成数
*/
private long failureGenerated;

/**
* 加密生成数
*/
private long encryptedGenerated;

/**
* 业务处理数
*/
private long businessProcessed;

/**
* 秒杀处理数
*/
private long seckillProcessed;

/**
* 库存处理数
*/
private long inventoryProcessed;

/**
* 平均生成时间(毫秒)
*/
private double averageGenerateTime;

/**
* 最后生成时间
*/
private LocalDateTime lastGenerateTime;

/**
* 生成器状态
*/
private String status;

public EcommerceGeneratorStatus() {
this.status = "ACTIVE";
}

public EcommerceGeneratorStatus(String generatorType) {
this();
this.generatorType = generatorType;
}

/**
* 计算成功率
* @return 成功率
*/
public double calculateSuccessRate() {
if (totalGenerated > 0) {
return (double) successGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算加密率
* @return 加密率
*/
public double calculateEncryptionRate() {
if (totalGenerated > 0) {
return (double) encryptedGenerated / totalGenerated;
}
return 0.0;
}

/**
* 计算业务处理率
* @return 业务处理率
*/
public double calculateBusinessProcessRate() {
if (totalGenerated > 0) {
return (double) businessProcessed / totalGenerated;
}
return 0.0;
}

/**
* 计算秒杀处理率
* @return 秒杀处理率
*/
public double calculateSeckillProcessRate() {
if (totalGenerated > 0) {
return (double) seckillProcessed / totalGenerated;
}
return 0.0;
}

/**
* 计算库存处理率
* @return 库存处理率
*/
public double calculateInventoryProcessRate() {
if (totalGenerated > 0) {
return (double) inventoryProcessed / totalGenerated;
}
return 0.0;
}

/**
* 是否健康
* @return 是否健康
*/
public boolean isHealthy() {
return calculateSuccessRate() >= 0.999 &&
calculateEncryptionRate() >= 0.999 &&
calculateBusinessProcessRate() >= 0.999 &&
calculateSeckillProcessRate() >= 0.999 &&
calculateInventoryProcessRate() >= 0.999;
}
}

2.4 基础电商分布式ID服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/**
* 基础电商分布式ID服务
* @author Java实战
*/
@Service
@Slf4j
public class EcommerceDistributedIdService {

@Autowired
private EcommerceDistributedIdProperties properties;

@Autowired
private EcommerceSnowflakeIdGenerator ecommerceSnowflakeIdGenerator;

@Autowired
private EcommerceUuidGenerator ecommerceUuidGenerator;

@Autowired
private EcommerceDatabaseIdGenerator ecommerceDatabaseIdGenerator;

@Autowired
private EcommerceRedisIdGenerator ecommerceRedisIdGenerator;

@Autowired
private EcommerceZookeeperIdGenerator ecommerceZookeeperIdGenerator;

@Autowired
private EcommerceDistributedIdMonitorService ecommerceDistributedIdMonitorService;

@Autowired
private EcommerceDistributedIdBusinessService ecommerceDistributedIdBusinessService;

@Autowired
private EcommerceDistributedIdSeckillService ecommerceDistributedIdSeckillService;

@Autowired
private EcommerceDistributedIdRepository ecommerceDistributedIdRepository;

/**
* 生成电商分布式ID
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @return 生成结果
*/
public EcommerceDistributedIdResult generateEcommerceId(String idType, String businessType, String ecommerceBusinessType) {
return generateEcommerceId(idType, businessType, ecommerceBusinessType, properties.getDefaultGeneratorType());
}

/**
* 生成电商分布式ID(指定生成器)
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param generatorType 生成器类型
* @return 生成结果
*/
public EcommerceDistributedIdResult generateEcommerceId(String idType, String businessType, String ecommerceBusinessType, String generatorType) {
log.info("生成电商分布式ID,ID类型: {}, 业务类型: {}, 电商业务类型: {}, 生成器类型: {}",
idType, businessType, ecommerceBusinessType, generatorType);

EcommerceDistributedIdResult result = new EcommerceDistributedIdResult();
result.setIdType(idType);
result.setBusinessType(businessType);
result.setEcommerceBusinessType(ecommerceBusinessType);
result.setGeneratorType(generatorType);
result.setStartTime(System.currentTimeMillis());

try {
// 参数验证
validateParameters(idType, businessType, ecommerceBusinessType, generatorType, result);
if (!result.isSuccess()) {
return result;
}

// 业务处理
if (!performBusinessProcess(idType, businessType, ecommerceBusinessType, result)) {
return result;
}

// 秒杀处理
if (!performSeckillProcess(idType, businessType, ecommerceBusinessType, result)) {
return result;
}

// 库存处理
if (!performInventoryProcess(idType, businessType, ecommerceBusinessType, result)) {
return result;
}

// 根据生成器类型生成ID
String id = generateIdByType(generatorType, idType, businessType, ecommerceBusinessType);

if (id != null && !id.isEmpty()) {
result.setSuccess(true);
result.setId(id);
result.setGenerateTime(LocalDateTime.now());
result.setEndTime(System.currentTimeMillis());

// 加密ID
if (properties.getSnowflake().isEnableEncryption()) {
id = encryptId(id, generatorType);
result.setId(id);
}

// 记录成功指标
ecommerceDistributedIdMonitorService.recordSuccessGeneration(generatorType, result.getDuration());

// 保存ID记录
saveEcommerceIdRecord(result);

log.info("电商分布式ID生成成功,ID: {}, 类型: {}, 生成器: {}", id, idType, generatorType);
} else {
result.setSuccess(false);
result.setError("ID生成失败");
result.setEndTime(System.currentTimeMillis());

// 记录失败指标
ecommerceDistributedIdMonitorService.recordFailureGeneration(generatorType);

log.warn("电商分布式ID生成失败,类型: {}, 生成器: {}", idType, generatorType);
}

return result;

} catch (Exception e) {
log.error("电商分布式ID生成异常,类型: {}, 生成器: {}", idType, generatorType, e);

result.setSuccess(false);
result.setError("电商分布式ID生成异常: " + e.getMessage());
result.setEndTime(System.currentTimeMillis());

// 记录失败指标
ecommerceDistributedIdMonitorService.recordFailureGeneration(generatorType);

return result;
}
}

/**
* 验证参数
*/
private void validateParameters(String idType, String businessType, String ecommerceBusinessType,
String generatorType, EcommerceDistributedIdResult result) {
if (idType == null || idType.isEmpty()) {
result.setSuccess(false);
result.setError("ID类型不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}

if (businessType == null || businessType.isEmpty()) {
result.setSuccess(false);
result.setError("业务类型不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}

if (ecommerceBusinessType == null || ecommerceBusinessType.isEmpty()) {
result.setSuccess(false);
result.setError("电商业务类型不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}

if (generatorType == null || generatorType.isEmpty()) {
result.setSuccess(false);
result.setError("生成器类型不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}
}

/**
* 执行业务处理
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param result 生成结果
* @return 是否通过业务处理
*/
private boolean performBusinessProcess(String idType, String businessType, String ecommerceBusinessType,
EcommerceDistributedIdResult result) {
try {
if (properties.getBusiness().isEnableBusinessIsolation()) {
Map<String, Object> businessInfo = ecommerceDistributedIdBusinessService.performBusinessProcess(
idType, businessType, ecommerceBusinessType);

result.setBusinessInfo(businessInfo);

if (businessInfo.containsKey("businessStatus") && "FAILED".equals(businessInfo.get("businessStatus"))) {
result.setSuccess(false);
result.setError("业务处理失败");
result.setEndTime(System.currentTimeMillis());
return false;
}

result.setBusinessStatus("BUSINESS_PROCESSED");
}

return true;

} catch (Exception e) {
log.error("业务处理异常", e);
return false;
}
}

/**
* 执行秒杀处理
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param result 生成结果
* @return 是否通过秒杀处理
*/
private boolean performSeckillProcess(String idType, String businessType, String ecommerceBusinessType,
EcommerceDistributedIdResult result) {
try {
if (properties.getSeckill().isEnableSeckill()) {
Map<String, Object> seckillInfo = ecommerceDistributedIdSeckillService.performSeckillProcess(
idType, businessType, ecommerceBusinessType);

result.setSeckillInfo(seckillInfo);

if (seckillInfo.containsKey("seckillStatus") && "FAILED".equals(seckillInfo.get("seckillStatus"))) {
result.setSuccess(false);
result.setError("秒杀处理失败");
result.setEndTime(System.currentTimeMillis());
return false;
}

result.setSeckillStatus("SECKILL_PROCESSED");
}

return true;

} catch (Exception e) {
log.error("秒杀处理异常", e);
return false;
}
}

/**
* 执行库存处理
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param result 生成结果
* @return 是否通过库存处理
*/
private boolean performInventoryProcess(String idType, String businessType, String ecommerceBusinessType,
EcommerceDistributedIdResult result) {
try {
if (properties.getInventory().isEnableInventory()) {
Map<String, Object> inventoryInfo = new HashMap<>();
inventoryInfo.put("idType", idType);
inventoryInfo.put("businessType", businessType);
inventoryInfo.put("ecommerceBusinessType", ecommerceBusinessType);
inventoryInfo.put("processTime", LocalDateTime.now());
inventoryInfo.put("inventoryStatus", "INVENTORY_PROCESSED");

result.setInventoryInfo(inventoryInfo);
result.setInventoryStatus("INVENTORY_PROCESSED");
}

return true;

} catch (Exception e) {
log.error("库存处理异常", e);
return false;
}
}

/**
* 根据生成器类型生成ID
* @param generatorType 生成器类型
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @return 生成的ID
*/
private String generateIdByType(String generatorType, String idType, String businessType, String ecommerceBusinessType) {
switch (generatorType.toUpperCase()) {
case "ECOMMERCE_SNOWFLAKE":
if (properties.getSnowflake().isEnableSnowflake()) {
return String.valueOf(ecommerceSnowflakeIdGenerator.nextId());
}
break;
case "ECOMMERCE_UUID":
if (properties.getUuid().isEnableUuid()) {
return ecommerceUuidGenerator.generateEcommerceUuid();
}
break;
case "ECOMMERCE_DATABASE":
if (properties.getDatabase().isEnableDatabase()) {
return String.valueOf(ecommerceDatabaseIdGenerator.nextId());
}
break;
case "ECOMMERCE_REDIS":
if (properties.getRedis().isEnableRedis()) {
return String.valueOf(ecommerceRedisIdGenerator.nextId());
}
break;
case "ECOMMERCE_ZOOKEEPER":
if (properties.getZookeeper().isEnableZookeeper()) {
return String.valueOf(ecommerceZookeeperIdGenerator.nextId());
}
break;
default:
log.warn("不支持的生成器类型: {}", generatorType);
return null;
}

log.warn("生成器类型 {} 未启用", generatorType);
return null;
}

/**
* 加密ID
* @param id ID
* @param generatorType 生成器类型
* @return 加密后的ID
*/
private String encryptId(String id, String generatorType) {
try {
String encryptionKey = getEncryptionKey(generatorType);
return AESUtil.encrypt(id, encryptionKey);
} catch (Exception e) {
log.error("ID加密异常", e);
return id;
}
}

/**
* 获取加密密钥
* @param generatorType 生成器类型
* @return 加密密钥
*/
private String getEncryptionKey(String generatorType) {
switch (generatorType.toUpperCase()) {
case "ECOMMERCE_SNOWFLAKE":
return properties.getSnowflake().getEncryptionKey();
case "ECOMMERCE_UUID":
return properties.getUuid().getEncryptionKey();
case "ECOMMERCE_DATABASE":
return properties.getDatabase().getEncryptionKey();
case "ECOMMERCE_REDIS":
return properties.getRedis().getEncryptionKey();
case "ECOMMERCE_ZOOKEEPER":
return properties.getZookeeper().getEncryptionKey();
default:
return "default-ecommerce-key";
}
}

/**
* 保存电商ID记录
* @param result 生成结果
*/
private void saveEcommerceIdRecord(EcommerceDistributedIdResult result) {
try {
EcommerceDistributedIdData data = new EcommerceDistributedIdData(
result.getId(),
result.getIdType(),
result.getGeneratorType()
);
data.setBusinessType(result.getBusinessType());
data.setEcommerceBusinessType(result.getEcommerceBusinessType());
data.setGenerateTime(result.getGenerateTime());
data.setEncryptionStatus(result.getEncryptionStatus());
data.setBusinessStatus(result.getBusinessStatus());
data.setSeckillStatus(result.getSeckillStatus());
data.setInventoryStatus(result.getInventoryStatus());
data.setExtendedPropertiesMap(result.getExtendedProperties());
data.setBusinessInfo(result.getBusinessInfo());
data.setSeckillInfo(result.getSeckillInfo());
data.setInventoryInfo(result.getInventoryInfo());

ecommerceDistributedIdRepository.save(data);

} catch (Exception e) {
log.error("保存电商ID记录异常", e);
}
}

/**
* 批量生成电商分布式ID
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param count 生成数量
* @return 生成结果列表
*/
public List<EcommerceDistributedIdResult> batchGenerateEcommerceId(String idType, String businessType,
String ecommerceBusinessType, int count) {
return batchGenerateEcommerceId(idType, businessType, ecommerceBusinessType, count, properties.getDefaultGeneratorType());
}

/**
* 批量生成电商分布式ID(指定生成器)
* @param idType ID类型
* @param businessType 业务类型
* @param ecommerceBusinessType 电商业务类型
* @param count 生成数量
* @param generatorType 生成器类型
* @return 生成结果列表
*/
public List<EcommerceDistributedIdResult> batchGenerateEcommerceId(String idType, String businessType,
String ecommerceBusinessType, int count, String generatorType) {
log.info("批量生成电商分布式ID,ID类型: {}, 业务类型: {}, 电商业务类型: {}, 数量: {}, 生成器类型: {}",
idType, businessType, ecommerceBusinessType, count, generatorType);

List<EcommerceDistributedIdResult> results = new ArrayList<>();

try {
for (int i = 0; i < count; i++) {
EcommerceDistributedIdResult result = generateEcommerceId(idType, businessType, ecommerceBusinessType, generatorType);
results.add(result);
}

log.info("批量生成电商分布式ID完成,成功数量: {}",
results.stream().mapToInt(r -> r.isSuccess() ? 1 : 0).sum());

} catch (Exception e) {
log.error("批量生成电商分布式ID异常", e);
}

return results;
}

/**
* 获取电商分布式ID状态
* @return 电商分布式ID状态
*/
public EcommerceDistributedIdStatus getEcommerceDistributedIdStatus() {
log.info("获取电商分布式ID状态");

try {
return ecommerceDistributedIdMonitorService.getStatus();
} catch (Exception e) {
log.error("获取电商分布式ID状态异常", e);
return null;
}
}

/**
* 验证电商ID格式
* @param id ID
* @param idType ID类型
* @return 是否有效
*/
public boolean validateEcommerceIdFormat(String id, String idType) {
log.info("验证电商ID格式,ID: {}, 类型: {}", id, idType);

try {
if (id == null || id.isEmpty()) {
return false;
}

// 解密ID
String decryptedId = decryptId(id, idType);

switch (idType.toUpperCase()) {
case "ECOMMERCE_SNOWFLAKE":
return validateEcommerceSnowflakeId(decryptedId);
case "ECOMMERCE_UUID":
return validateEcommerceUuid(decryptedId);
case "ECOMMERCE_DATABASE":
return validateEcommerceDatabaseId(decryptedId);
case "ECOMMERCE_REDIS":
return validateEcommerceRedisId(decryptedId);
case "ECOMMERCE_ZOOKEEPER":
return validateEcommerceZookeeperId(decryptedId);
default:
return false;
}

} catch (Exception e) {
log.error("验证电商ID格式异常", e);
return false;
}
}

/**
* 解密ID
* @param id ID
* @param idType ID类型
* @return 解密后的ID
*/
private String decryptId(String id, String idType) {
try {
String encryptionKey = getEncryptionKey(idType);
return AESUtil.decrypt(id, encryptionKey);
} catch (Exception e) {
log.error("ID解密异常", e);
return id;
}
}

/**
* 验证电商雪花算法ID
* @param id ID
* @return 是否有效
*/
private boolean validateEcommerceSnowflakeId(String id) {
try {
long idLong = Long.parseLong(id);
return idLong > 0;
} catch (NumberFormatException e) {
return false;
}
}

/**
* 验证电商UUID
* @param id ID
* @return 是否有效
*/
private boolean validateEcommerceUuid(String id) {
try {
UUID.fromString(id);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}

/**
* 验证电商数据库ID
* @param id ID
* @return 是否有效
*/
private boolean validateEcommerceDatabaseId(String id) {
try {
long idLong = Long.parseLong(id);
return idLong > 0;
} catch (NumberFormatException e) {
return false;
}
}

/**
* 验证电商Redis ID
* @param id ID
* @return 是否有效
*/
private boolean validateEcommerceRedisId(String id) {
try {
long idLong = Long.parseLong(id);
return idLong > 0;
} catch (NumberFormatException e) {
return false;
}
}

/**
* 验证电商Zookeeper ID
* @param id ID
* @return 是否有效
*/
private boolean validateEcommerceZookeeperId(String id) {
try {
long idLong = Long.parseLong(id);
return idLong > 0;
} catch (NumberFormatException e) {
return false;
}
}
}

3. 高级功能实现

3.1 电商雪花算法ID生成器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/**
* 电商雪花算法ID生成器
* @author Java实战
*/
@Component
@Slf4j
public class EcommerceSnowflakeIdGenerator {

@Autowired
private EcommerceDistributedIdProperties properties;

// 开始时间戳 (2021-01-01 00:00:00)
private final long startTimestamp = 1609459200000L;

// 序列号占用的位数
private final long sequenceBits = 10L;

// 机器标识占用的位数
private final long workerIdBits = 5L;

// 数据中心标识占用的位数
private final long datacenterIdBits = 5L;

// 电商标识占用的位数
private final long ecommerceIdBits = 4L;

// 时间戳占用的位数
private final long timestampBits = 40L;

// 机器ID最大值
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

// 数据中心ID最大值
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

// 电商ID最大值
private final long maxEcommerceId = -1L ^ (-1L << ecommerceIdBits);

// 序列号最大值
private final long maxSequence = -1L ^ (-1L << sequenceBits);

// 机器ID左移位数
private final long workerIdShift = sequenceBits;

// 数据中心ID左移位数
private final long datacenterIdShift = sequenceBits + workerIdBits;

// 电商ID左移位数
private final long ecommerceIdShift = sequenceBits + workerIdBits + datacenterIdBits;

// 时间戳左移位数
private final long timestampShift = sequenceBits + workerIdBits + datacenterIdBits + ecommerceIdBits;

// 工作机器ID
private long workerId;

// 数据中心ID
private long datacenterId;

// 电商ID
private long ecommerceId;

// 序列号
private long sequence = 0L;

// 上次生成ID的时间戳
private long lastTimestamp = -1L;

/**
* 构造函数
* @param workerId 工作机器ID
* @param datacenterId 数据中心ID
* @param ecommerceId 电商ID
*/
public EcommerceSnowflakeIdGenerator(long workerId, long datacenterId, long ecommerceId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
if (ecommerceId > maxEcommerceId || ecommerceId < 0) {
throw new IllegalArgumentException(String.format("ecommerce Id can't be greater than %d or less than 0", maxEcommerceId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
this.ecommerceId = ecommerceId;
}

/**
* 生成下一个ID
* @return 下一个ID
*/
public synchronized long nextId() {
long timestamp = timeGen();

// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}

// 如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & maxSequence;
// 毫秒内序列溢出
if (sequence == 0) {
// 阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
} else {
// 时间戳改变,毫秒内序列重置
sequence = 0L;
}

// 上次生成ID的时间戳
lastTimestamp = timestamp;

// 移位并通过或运算拼到一起组成64位的ID
return ((timestamp - startTimestamp) << timestampShift) //
| (ecommerceId << ecommerceIdShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}

/**
* 阻塞到下一个毫秒,直到获得新的时间戳
* @param lastTimestamp 上次生成ID的时间戳
* @return 当前时间戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}

/**
* 返回以毫秒为单位的当前时间
* @return 当前时间(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}

/**
* 解析电商雪花算法ID
* @param id 电商雪花算法ID
* @return 解析结果
*/
public Map<String, Object> parseEcommerceId(long id) {
Map<String, Object> result = new HashMap<>();

// 时间戳
long timestamp = (id >> timestampShift) + startTimestamp;
result.put("timestamp", timestamp);
result.put("datetime", new Date(timestamp));

// 电商ID
long ecommerceId = (id >> ecommerceIdShift) & maxEcommerceId;
result.put("ecommerceId", ecommerceId);

// 数据中心ID
long datacenterId = (id >> datacenterIdShift) & maxDatacenterId;
result.put("datacenterId", datacenterId);

// 机器ID
long workerId = (id >> workerIdShift) & maxWorkerId;
result.put("workerId", workerId);

// 序列号
long sequence = id & maxSequence;
result.put("sequence", sequence);

return result;
}

/**
* 获取工作机器ID
* @return 工作机器ID
*/
public long getWorkerId() {
return workerId;
}

/**
* 获取数据中心ID
* @return 数据中心ID
*/
public long getDatacenterId() {
return datacenterId;
}

/**
* 获取电商ID
* @return 电商ID
*/
public long getEcommerceId() {
return ecommerceId;
}

/**
* 获取序列号
* @return 序列号
*/
public long getSequence() {
return sequence;
}

/**
* 获取上次生成ID的时间戳
* @return 上次生成ID的时间戳
*/
public long getLastTimestamp() {
return lastTimestamp;
}

/**
* 获取配置信息
* @return 配置信息
*/
public Map<String, Object> getConfig() {
Map<String, Object> config = new HashMap<>();
config.put("workerId", workerId);
config.put("datacenterId", datacenterId);
config.put("ecommerceId", ecommerceId);
config.put("startTimestamp", startTimestamp);
config.put("sequenceBits", sequenceBits);
config.put("workerIdBits", workerIdBits);
config.put("datacenterIdBits", datacenterIdBits);
config.put("ecommerceIdBits", ecommerceIdBits);
config.put("timestampBits", timestampBits);
config.put("maxWorkerId", maxWorkerId);
config.put("maxDatacenterId", maxDatacenterId);
config.put("maxEcommerceId", maxEcommerceId);
config.put("maxSequence", maxSequence);
return config;
}
}

3.2 电商UUID生成器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* 电商UUID生成器
* @author Java实战
*/
@Component
@Slf4j
public class EcommerceUuidGenerator {

@Autowired
private EcommerceDistributedIdProperties properties;

/**
* 生成电商UUID
* @return 电商UUID字符串
*/
public String generateEcommerceUuid() {
return generateEcommerceUuid(properties.getUuid().getVersion());
}

/**
* 生成指定版本的电商UUID
* @param version UUID版本
* @return 电商UUID字符串
*/
public String generateEcommerceUuid(String version) {
log.info("生成电商UUID,版本: {}", version);

try {
UUID uuid;

switch (version.toUpperCase()) {
case "UUID1":
uuid = generateEcommerceUuid1();
break;
case "UUID3":
uuid = generateEcommerceUuid3();
break;
case "UUID4":
uuid = generateEcommerceUuid4();
break;
case "UUID5":
uuid = generateEcommerceUuid5();
break;
default:
uuid = generateEcommerceUuid4();
break;
}

String uuidString = uuid.toString();

// 根据配置处理格式
if (!properties.getUuid().isUseHyphens()) {
uuidString = uuidString.replace("-", "");
}

if (properties.getUuid().isUseUpperCase()) {
uuidString = uuidString.toUpperCase();
}

log.info("电商UUID生成成功,UUID: {}", uuidString);

return uuidString;

} catch (Exception e) {
log.error("电商UUID生成异常", e);
return null;
}
}

/**
* 生成电商UUID1(基于时间戳)
* @return 电商UUID1
*/
private UUID generateEcommerceUuid1() {
return UUID.randomUUID(); // Java的UUID.randomUUID()实际上是UUID4,这里简化处理
}

/**
* 生成电商UUID3(基于MD5)
* @return 电商UUID3
*/
private UUID generateEcommerceUuid3() {
String namespace = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; // DNS namespace
String name = "ecommerce-distributed-id";
return UUID.nameUUIDFromBytes((namespace + name).getBytes());
}

/**
* 生成电商UUID4(随机)
* @return 电商UUID4
*/
private UUID generateEcommerceUuid4() {
return UUID.randomUUID();
}

/**
* 生成电商UUID5(基于SHA-1)
* @return 电商UUID5
*/
private UUID generateEcommerceUuid5() {
String namespace = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; // DNS namespace
String name = "ecommerce-distributed-id";
return UUID.nameUUIDFromBytes((namespace + name).getBytes());
}

/**
* 生成电商短UUID(8位)
* @return 电商短UUID
*/
public String generateEcommerceShortUuid() {
log.info("生成电商短UUID");

try {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString().replace("-", "");

// 取前8位
String shortUuid = uuidString.substring(0, 8);

log.info("电商短UUID生成成功,UUID: {}", shortUuid);

return shortUuid;

} catch (Exception e) {
log.error("电商短UUID生成异常", e);
return null;
}
}

/**
* 生成电商数字UUID(纯数字)
* @return 电商数字UUID
*/
public String generateEcommerceNumericUuid() {
log.info("生成电商数字UUID");

try {
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString().replace("-", "");

// 转换为数字
StringBuilder numericUuid = new StringBuilder();
for (char c : uuidString.toCharArray()) {
if (Character.isDigit(c)) {
numericUuid.append(c);
} else {
// 将字母转换为数字
numericUuid.append((int) c % 10);
}
}

String result = numericUuid.toString();

log.info("电商数字UUID生成成功,UUID: {}", result);

return result;

} catch (Exception e) {
log.error("电商数字UUID生成异常", e);
return null;
}
}

/**
* 验证电商UUID格式
* @param uuid 电商UUID字符串
* @return 是否有效
*/
public boolean validateEcommerceUuid(String uuid) {
log.info("验证电商UUID格式,UUID: {}", uuid);

try {
if (uuid == null || uuid.isEmpty()) {
return false;
}

// 尝试解析UUID
UUID.fromString(uuid);

log.info("电商UUID格式验证成功");

return true;

} catch (IllegalArgumentException e) {
log.warn("电商UUID格式验证失败", e);
return false;
}
}

/**
* 获取电商UUID版本
* @param uuid 电商UUID字符串
* @return 电商UUID版本
*/
public int getEcommerceUuidVersion(String uuid) {
log.info("获取电商UUID版本,UUID: {}", uuid);

try {
UUID uuidObj = UUID.fromString(uuid);
int version = uuidObj.version();

log.info("电商UUID版本获取成功,版本: {}", version);

return version;

} catch (IllegalArgumentException e) {
log.error("获取电商UUID版本异常", e);
return -1;
}
}

/**
* 获取电商UUID变体
* @param uuid 电商UUID字符串
* @return 电商UUID变体
*/
public int getEcommerceUuidVariant(String uuid) {
log.info("获取电商UUID变体,UUID: {}", uuid);

try {
UUID uuidObj = UUID.fromString(uuid);
int variant = uuidObj.variant();

log.info("电商UUID变体获取成功,变体: {}", variant);

return variant;

} catch (IllegalArgumentException e) {
log.error("获取电商UUID变体异常", e);
return -1;
}
}

/**
* 获取配置信息
* @return 配置信息
*/
public Map<String, Object> getConfig() {
Map<String, Object> config = new HashMap<>();
config.put("version", properties.getUuid().getVersion());
config.put("useHyphens", properties.getUuid().isUseHyphens());
config.put("useUpperCase", properties.getUuid().isUseUpperCase());
config.put("enableEncryption", properties.getUuid().isEnableEncryption());
config.put("encryptionKey", properties.getUuid().getEncryptionKey());
return config;
}
}

4. 电商分布式ID控制器

4.1 电商分布式ID REST控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* 电商分布式ID REST控制器
* @author Java实战
*/
@RestController
@RequestMapping("/api/ecommerce-distributed-id")
@Slf4j
public class EcommerceDistributedIdController {

@Autowired
private EcommerceDistributedIdService ecommerceDistributedIdService;

@Autowired
private EcommerceDistributedIdMonitorService ecommerceDistributedIdMonitorService;

/**
* 生成电商分布式ID
* @param request 生成请求
* @return 生成结果
*/
@PostMapping("/generate")
public ResponseEntity<EcommerceDistributedIdResult> generateEcommerceId(@RequestBody EcommerceDistributedIdGenerateRequest request) {
try {
log.info("接收到生成电商分布式ID请求,ID类型: {}", request.getIdType());

// 参数验证
if (request.getIdType() == null || request.getIdType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getBusinessType() == null || request.getBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getEcommerceBusinessType() == null || request.getEcommerceBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

EcommerceDistributedIdResult result = ecommerceDistributedIdService.generateEcommerceId(
request.getIdType(),
request.getBusinessType(),
request.getEcommerceBusinessType(),
request.getGeneratorType()
);

return ResponseEntity.ok(result);

} catch (Exception e) {
log.error("生成电商分布式ID失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 批量生成电商分布式ID
* @param request 批量生成请求
* @return 生成结果列表
*/
@PostMapping("/batch-generate")
public ResponseEntity<List<EcommerceDistributedIdResult>> batchGenerateEcommerceId(@RequestBody EcommerceDistributedIdBatchGenerateRequest request) {
try {
log.info("接收到批量生成电商分布式ID请求,ID类型: {}, 数量: {}", request.getIdType(), request.getCount());

if (request.getIdType() == null || request.getIdType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getBusinessType() == null || request.getBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getEcommerceBusinessType() == null || request.getEcommerceBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getCount() <= 0 || request.getCount() > 1000) {
return ResponseEntity.badRequest().build();
}

List<EcommerceDistributedIdResult> results = ecommerceDistributedIdService.batchGenerateEcommerceId(
request.getIdType(),
request.getBusinessType(),
request.getEcommerceBusinessType(),
request.getCount(),
request.getGeneratorType()
);

return ResponseEntity.ok(results);

} catch (Exception e) {
log.error("批量生成电商分布式ID失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 验证电商ID格式
* @param id ID
* @param idType ID类型
* @return 是否有效
*/
@GetMapping("/validate")
public ResponseEntity<Boolean> validateEcommerceIdFormat(
@RequestParam String id,
@RequestParam String idType) {
try {
log.info("接收到验证电商ID格式请求,ID: {}, 类型: {}", id, idType);

if (id == null || id.isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (idType == null || idType.isEmpty()) {
return ResponseEntity.badRequest().build();
}

boolean valid = ecommerceDistributedIdService.validateEcommerceIdFormat(id, idType);

return ResponseEntity.ok(valid);

} catch (Exception e) {
log.error("验证电商ID格式失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取电商分布式ID状态
* @return 电商分布式ID状态
*/
@GetMapping("/status")
public ResponseEntity<EcommerceDistributedIdStatus> getEcommerceDistributedIdStatus() {
try {
log.info("接收到获取电商分布式ID状态请求");

EcommerceDistributedIdStatus status = ecommerceDistributedIdService.getEcommerceDistributedIdStatus();

return ResponseEntity.ok(status);

} catch (Exception e) {
log.error("获取电商分布式ID状态失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取电商分布式ID监控指标
* @return 监控指标
*/
@GetMapping("/metrics")
public ResponseEntity<EcommerceDistributedIdMetrics> getEcommerceDistributedIdMetrics() {
try {
EcommerceDistributedIdMetrics metrics = ecommerceDistributedIdMonitorService.getMetrics();
return ResponseEntity.ok(metrics);
} catch (Exception e) {
log.error("获取电商分布式ID监控指标失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 健康检查
* @return 健康状态
*/
@GetMapping("/health")
public ResponseEntity<Map<String, Object>> healthCheck() {
try {
Map<String, Object> health = new HashMap<>();

EcommerceDistributedIdStatus status = ecommerceDistributedIdService.getEcommerceDistributedIdStatus();

health.put("status", status != null && status.isHealthy() ? "UP" : "DOWN");
health.put("timestamp", System.currentTimeMillis());
health.put("details", status);

return ResponseEntity.ok(health);

} catch (Exception e) {
log.error("健康检查失败", e);

Map<String, Object> health = new HashMap<>();
health.put("status", "DOWN");
health.put("timestamp", System.currentTimeMillis());
health.put("error", e.getMessage());

return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(health);
}
}
}

/**
* 电商分布式ID生成请求类
* @author Java实战
*/
@Data
public class EcommerceDistributedIdGenerateRequest {

/**
* ID类型
*/
@NotBlank(message = "ID类型不能为空")
private String idType;

/**
* 业务类型
*/
@NotBlank(message = "业务类型不能为空")
private String businessType;

/**
* 电商业务类型
*/
@NotBlank(message = "电商业务类型不能为空")
private String ecommerceBusinessType;

/**
* 生成器类型
*/
private String generatorType;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

public EcommerceDistributedIdGenerateRequest() {
this.extendedProperties = new HashMap<>();
}
}

/**
* 电商分布式ID批量生成请求类
* @author Java实战
*/
@Data
public class EcommerceDistributedIdBatchGenerateRequest {

/**
* ID类型
*/
@NotBlank(message = "ID类型不能为空")
private String idType;

/**
* 业务类型
*/
@NotBlank(message = "业务类型不能为空")
private String businessType;

/**
* 电商业务类型
*/
@NotBlank(message = "电商业务类型不能为空")
private String ecommerceBusinessType;

/**
* 生成数量
*/
@Min(value = 1, message = "生成数量必须大于0")
@Max(value = 1000, message = "生成数量不能超过1000")
private int count;

/**
* 生成器类型
*/
private String generatorType;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

public EcommerceDistributedIdBatchGenerateRequest() {
this.extendedProperties = new HashMap<>();
}
}

5. 总结

5.1 电商分布式ID最佳实践

  1. 合理选择生成方案: 根据电商业务场景选择合适的分布式ID生成方案
  2. 性能优化: 优化ID生成性能,减少延迟
  3. 高可用设计: 确保ID生成服务的高可用性
  4. 监控告警: 实时监控ID生成状态和性能
  5. 安全考虑: 避免暴露电商业务信息
  6. 业务隔离: 支持不同业务模块的ID隔离
  7. 秒杀支持: 支持高并发秒杀场景
  8. 库存管理: 支持库存管理和防超卖

5.2 性能优化建议

  • 缓存策略: 合理使用缓存减少数据库访问
  • 批量生成: 支持批量ID生成提高效率
  • 连接池优化: 优化数据库连接池配置
  • 异步处理: 异步处理非关键路径
  • 负载均衡: 合理分配ID生成负载
  • 加密优化: 优化加密算法性能

5.3 运维管理要点

  • 实时监控: 监控ID生成状态和性能
  • 故障处理: 建立完善的故障处理机制
  • 性能调优: 根据监控数据优化性能
  • 日志管理: 完善日志记录和分析
  • 容量规划: 合理规划ID生成容量
  • 业务管理: 确保符合电商业务需求
  • 秒杀管理: 完善秒杀场景支持
  • 库存管理: 建立完善库存控制机制

通过本文的电商分布式ID Java实战指南,您可以掌握电商级分布式ID生成方案的原理、实现细节、性能优化技巧以及在企业级电商应用中的最佳实践,构建高效、可靠、业务友好的电商分布式ID生成系统!