ningshuxia
2024-04-29 6eb4d5574aee7042b1883e043d5798865e84d1d1
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
namespace IStation
{
    /// <summary>
    /// 雪花Id辅助类
    /// </summary>
    public class SnowflakeIdHelper
    {
 
        SnowflakeIdHelper()
        {
            var options = new IdGeneratorOptions(1); //构造方法初始化雪花Id 
            YitIdHelper.SetIdGenerator(options);
        }
 
        private static IIdGenerator _IdGenInstance = null;
        public static IIdGenerator IdGenInstance => _IdGenInstance;
 
        /// <summary> 
        /// 设置参数,建议程序初始化时执行一次 
        /// </summary> 
        /// <param name="workerId">workerId</param> 
        public static void SetIdGenerator(ushort workerId)
        {
            var options = new IdGeneratorOptions() { WorkerId = workerId };
            _IdGenInstance = new DefaultIdGenerator(options);
        }
 
        /// <summary> 
        /// 生成新的Id 
        /// 调用本方法前,请确保调用了 SetIdGenerator 方法做初始化。 
        /// 否则将会初始化一个WorkerId为1的对象。 
        /// </summary> 
        /// <returns></returns> 
        public static long NextId()
        {
            if (_IdGenInstance == null)
            {
                _IdGenInstance = new DefaultIdGenerator(
                new IdGeneratorOptions() { WorkerId = 0 }
                );
            }
            return _IdGenInstance.NewLong();
        }
 
    }
}