1- using Yitter . IdGenerator ;
1+ using Yitter . IdGenerator ;
22
33namespace GameFrameX . Utility ;
44
@@ -18,6 +18,16 @@ public static class IdGenerator
1818 /// 用于生成递增的整数ID
1919 /// </summary>
2020 private static int _intCounter = ( int ) ( DateTime . UtcNow - UtcTimeStart ) . TotalSeconds ;
21+
22+ /// <summary>
23+ /// 标记YitIdHelper是否已初始化
24+ /// </summary>
25+ private static bool _isYitIdInitialized = false ;
26+
27+ /// <summary>
28+ /// 用于同步YitIdHelper初始化的锁对象
29+ /// </summary>
30+ private static readonly object _initLock = new object ( ) ;
2131
2232 /// <summary>
2333 /// 使用Interlocked.Increment生成唯一的整数ID
@@ -35,11 +45,54 @@ public static int GetNextUniqueIntId()
3545 /// 基于Yitter.IdGenerator实现,提供分布式环境下的唯一ID生成
3646 /// </summary>
3747 /// <returns>返回下一个唯一的长整数ID,保证全局唯一性</returns>
48+ /// <exception cref="InvalidOperationException">当YitIdHelper初始化失败时抛出此异常</exception>
3849 public static long GetNextUniqueId ( )
3950 {
51+ // 确保YitIdHelper已初始化
52+ EnsureYitIdInitialized ( ) ;
53+
4054 // 使用雪花算法生成ID
4155 return YitIdHelper . NextId ( ) ;
4256 }
57+
58+ /// <summary>
59+ /// 确保YitIdHelper已正确初始化
60+ /// </summary>
61+ /// <exception cref="InvalidOperationException">当初始化失败时抛出此异常</exception>
62+ private static void EnsureYitIdInitialized ( )
63+ {
64+ if ( _isYitIdInitialized )
65+ {
66+ return ;
67+ }
68+
69+ lock ( _initLock )
70+ {
71+ if ( _isYitIdInitialized )
72+ {
73+ return ;
74+ }
75+
76+ try
77+ {
78+ // 使用默认配置初始化YitIdHelper
79+ // WorkerId设为1,确保在没有外部配置时也能正常工作
80+ var options = new IdGeneratorOptions ( 1 )
81+ {
82+ WorkerIdBitLength = 6 ,
83+ SeqBitLength = 6 ,
84+ BaseTime = UtcTimeStart
85+ } ;
86+
87+ YitIdHelper . SetIdGenerator ( options ) ;
88+ _isYitIdInitialized = true ;
89+ }
90+ catch ( Exception ex )
91+ {
92+ throw new InvalidOperationException ( "Failed to initialize YitIdHelper for ID generation." , ex ) ;
93+ }
94+ }
95+ }
4396
4497 /// <summary>
4598 /// 生成一个全局唯一的GUID字符串
0 commit comments