Ejemplo n.º 1
0
        public ResponseResult GetIdWorker(int count)
        {
            var result = new ResponseResult(0, "保存成功");

            try
            {
                List <string> workId = new List <string>();
                for (int i = 0; i < count; i++)
                {
                    var workerId = string.Empty;
                    System.Threading.Thread.Sleep(500);
                    workerId = new IdWorker(1, 1).NextId().ToString();
                    //workerId = Guid.NewGuid().ToString();
                    workId.Add(workerId);
                }
                result.Data = workId;
                return(result);
            }
            catch (Exception ex)
            {
                result.Code    = -1;
                result.Message = ex.Message;
                LogLock.WriteLine("SystemLog", new[] { ex.ToString() });
            }
            return(result);
        }
Ejemplo n.º 2
0
 static IdWorkerFactory()
 {
     if (IdWorker == null)
     {
         IdWorker = new IdWorker(1, 1);
     }
 }
Ejemplo n.º 3
0
        public void It_should_generate_an_id()
        {
            var worker = new IdWorker(1, 1);
            var v      = worker.NextId();

            Assert.That(v, Is.GreaterThan(0));
        }
Ejemplo n.º 4
0
 // 定义私有构造函数,使外界不能创建该类实例
 private SnowFlake_Net()
 {
     if (worker == null)
     {
         worker = new IdWorker(1, 1);
     }
 }
Ejemplo n.º 5
0
        public void It_should_generate_ids_over_50_billion()
        {
            var worker = new IdWorker(0, 0);
            var id     = worker.NextId();

            Assert.That(id, Is.GreaterThan(50000000000L));
        }
Ejemplo n.º 6
0
        // 布式全局唯一ID算法
        static void Main(string[] args)
        {
            var  worker = new IdWorker(1, 1);
            long id     = worker.NextId();

            Console.WriteLine(id);
        }
Ejemplo n.º 7
0
        public bool SaveChange(SysMember entity)
        {
            var snapshot = GetById(entity.ID);
            var rlt      = _baseQueryRepository.Context.Ado.UseTran(() =>
            {
                var userTemp = new sys_member();
                userTemp.Mapp(entity);
                var success = _baseQueryRepository.Context.Updateable(userTemp)
                              .Where(it => it.ID == entity.ID)
                              .ExecuteCommand();//主表
                snapshot.Roles.Where(r => !entity.Roles.Exists(rr => rr.ID == r.ID)).ToList().ForEach(r =>
                {
                    _baseQueryRepository.Context.Ado.ExecuteCommand("delete from sys_member_roles_link where mid=@mid and rid=@rid;"
                                                                    , new { mid = entity.ID, rid = r.ID });
                });

                entity.Roles.Where(r => !snapshot.Roles.Exists(rr => rr.ID == r.ID)).ToList().ForEach(r =>
                {
                    var smrlink = new sys_member_roles_link()
                    {
                        ID  = IdWorker.NextId(),
                        mid = entity.ID,
                        rid = r.ID
                    };
                    _baseQueryRepository.Context.Insertable(smrlink).ExecuteCommand();
                });
            });

            return(true);
        }
Ejemplo n.º 8
0
 public void Execute(SysFuncCommand command)
 {
     if (command.SysType == SysType.AddChild)
     {
         SysFunc sysFunc = new SysFunc(IdWorker.NextId());
         sysFunc.Mapp(command);
         sysFunc.Pid = command.Id;
         _sysFuncRepository.Add(sysFunc);
         command.Result.Status = true;
     }
     else if (command.SysType == SysType.AddFlatLevel)
     {
         SysFunc sysFunc = new SysFunc(IdWorker.NextId());
         sysFunc.Mapp(command);
         _sysFuncRepository.Add(sysFunc);
         command.Result.Status = true;
     }
     else if (command.SysType == SysType.Remove)
     {
         var rlt = _sysFuncRepository.Remove(command.Id);
         if (!rlt.success)
         {
             command.Result.Status = false;
             command.Result.Msg    = rlt.msg;
         }
         command.Result.Status = true;
     }
     else if (command.SysType == SysType.Update)
     {
         SysFunc sysFunc = new SysFunc();
         sysFunc.Mapp(command);
         _sysFuncRepository.SaveChange(sysFunc);
         command.Result.Status = true;
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 注册WebCore服务,配置网站
        /// do other things
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddWebCoreService(this IServiceCollection services, IConfiguration configuration)
        {
            //绑定appsetting中的SiteSetting
            services.Configure <SiteSetting>(configuration.GetSection(nameof(SiteSetting)));

            #region 单例化雪花算法
            string workIdStr       = configuration.GetSection("SiteSetting:WorkerId").Value;
            string datacenterIdStr = configuration.GetSection("SiteSetting:DataCenterId").Value;
            long   workId;
            long   datacenterId;
            try
            {
                workId       = long.Parse(workIdStr);
                datacenterId = long.Parse(datacenterIdStr);
            }
            catch (Exception)
            {
                throw;
            }
            IdWorker idWorker = new IdWorker(workId, datacenterId);
            services.AddSingleton(idWorker);

            #endregion
            return(services);
        }
Ejemplo n.º 10
0
 static NewId()
 {
     if (IdWorker == null)
     {
         IdWorker = new IdWorker(0, 0);
     }
 }
Ejemplo n.º 11
0
 static IdWorkerHelper()
 {
     if (worker == null)
     {
         worker = new IdWorker(1, 1);
     }
 }
Ejemplo n.º 12
0
 public UsersDbOperator(OtokatariContext context, ILogger <UsersDbOperator> loggger, IdWorker uid, SingersDbOperator singer)
 {
     _context = context;
     _logger  = loggger;
     _uid     = uid;
     _singer  = singer;
 }
Ejemplo n.º 13
0
        public void TestIdWorker()
        {
            HashSet <long> set       = new HashSet <long>();
            IdWorker       idWorker1 = new IdWorker(0, 0);
            IdWorker       idWorker2 = new IdWorker(1, 0);
            //762884413578018816
            //762884520121729024
            Stopwatch sw = new Stopwatch();

            sw.Start();
            for (int i = 0; i < 100; i++)
            {
                long id = idWorker1.NextId();
                set.Add(id);
                //if (!set.Add(id))
                //{
                //Console.WriteLine("duplicate:" + id);
                //}
            }
            sw.Stop();
            foreach (var item in set)
            {
                Console.WriteLine("结果:" + item);
            }
            Console.WriteLine("时间:" + sw.ElapsedTicks);
            return;
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 获取唯一ID
 /// </summary>
 /// <returns></returns>
 public static long GetId()
 {
     if (idWorker == null)
     {
         idWorker = new IdWorker(1, 1);
     }
     return(idWorker.NextId());
 }
Ejemplo n.º 15
0
 public BaseService(IUnitOfWork <PHDbContext> unitOfWork, IMapper mapper, IdWorker idWorker, IClaimsAccessor claimsAccessor, IStringLocalizer localizer)
 {
     _unitOfWork     = unitOfWork;
     _mapper         = mapper;
     _idWorker       = idWorker;
     _claimsAccessor = claimsAccessor;
     _localizer      = localizer;
 }
Ejemplo n.º 16
0
        public ActionResult TraceBatch()
        {
            List <sys_trace> traces = Request <List <sys_trace> >("traces");

            traces.ForEach(t => { t.ID = IdWorker.NextId(); });
            _db.Insertable <sys_trace>(traces).With(SqlWith.NoLock).ExecuteCommand();
            return(new ActionResult(true, null, null, null));
        }
Ejemplo n.º 17
0
 public void Setup()
 {
     this.mapleDataTest = new MapleDataTest();
     this.dapperDataTest = new DapperDataTest();
     this.efDataTest = new EFDataTest();
     this.idWorker = new IdWorker(0);
     this.mapleRepositoryDataTest = new MapleRepositoryDataTest();
 }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            var  worker = new IdWorker(1, 1);
            long id     = worker.NextId();

            Console.WriteLine($"生成的ID为:{id},他的长度是:{id.ToString().Length}");
            Console.ReadKey();
        }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            var  worker = new IdWorker(1, 1);
            long id     = worker.NextId();

            Console.WriteLine($"ID:{id} , Length:{id.ToString().Length}");
            Console.ReadKey();
        }
Ejemplo n.º 20
0
 public Circuit()
 {
     speed     = 172;
     snowflake = new IdWorker(1, 1);
     elements  = new List <ICircuitElement>();
     nodeMesh  = new List <long[]>();
     scopeMap  = new Dictionary <ICircuitElement, List <ScopeFrame> >();
 }
Ejemplo n.º 21
0
    /// <summary>
    /// 生成编号随机数+时间戳
    /// </summary>
    /// <returns></returns>
    public static string RandomCode()
    {
        IdWorker worker = new IdWorker(1);
        var      str    = worker.nextId().ToString();

        worker = null;
        return(str);
    }
Ejemplo n.º 22
0
 /// <summary>
 /// snowflake算法实例
 /// </summary>
 /// <returns></returns>
 private static IdWorker Instance()
 {
     if (snowflake == null)
     {
         //机器ID,数据中心ID
         snowflake = new IdWorker(1, 1);
     }
     return(snowflake);
 }
Ejemplo n.º 23
0
        public IdentifiedGenerateService(IClusterService clusterService)
        {
            if (clusterService == null || clusterService.ServerMember == null)
            {
                throw new SysException(ExcpetionCode.EX1100000.ToString(), Localization.Sy000000.ToString());
            }

            _idWorker = new IdWorker(clusterService.ServerMember.Id, 1);
        }
Ejemplo n.º 24
0
        protected AggregateRoot(long id)
        {
            if (id == 0)
            {
                id = new IdWorker(DateTime.Now.Ticks).NextId();
            }

            Id = id;
        }
Ejemplo n.º 25
0
        // 定义私有构造函数,使外界不能创建该类实例
        public SnowFlakeNetService(ConfigFileService configFileService)
        {
            var config = configFileService.WebConfig.IdGeneratorConfig;

            if (worker == null)
            {
                worker = new IdWorker(config.WorkerId, config.DatacenterId);
            }
        }
Ejemplo n.º 26
0
        public static long NewGuid()
        {
            var  worker = new IdWorker(1, 1);
            long id     = worker.NextId();

            //加上当前线程id 避免多线程下相同
            return(id + Thread.CurrentThread.ManagedThreadId);
            //return DateTimeOffset.UtcNow.Ticks + Guid.NewGuid().ToString("N");
        }
Ejemplo n.º 27
0
        protected Entity(long id)
        {
            if (id == 0)
            {
                id = new IdWorker(DateTime.Now.Ticks).NextId();
            }
            ;

            Id = id;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 使用snowFlake 产生唯一long型Id,自动递增,一般用于主键.
        /// </summary>
        /// <returns>long类型id.</returns>
        public static long NewGuid()
        {
            // var generator = new IdGenerator(0);
            // var id = generator.CreateId();
            var  worker = new IdWorker(1, 1);
            long id     = worker.NextId();

            // 加上当前线程id 避免多线程下相同
            return(id);
        }
Ejemplo n.º 29
0
        public BaseStorage(BaseStorageOptions options)
        {
            _options = options;

            _idWorker = new IdWorker(new Random().Next(1, 30), new Random().Next(1, 30));

            _deferFlushCollection = new AsyncCallbackDeferFlushCollection <RequestBag>(AddRequestInfoAsync, _options.DeferThreshold, _options.DeferSecond);

            freeSql = new FreeSql.FreeSqlBuilder().UseConnectionString(_options.DataType, _options.ConnectionString).UseNoneCommandParameter(true).Build();
        }
 public DefaultHttpReportsMiddleware(RequestDelegate next, IdWorker idWorker, JsonSerializerOptions jsonSetting, IOptions <HttpReportsOptions> options, IRequestBuilder requestBuilder, IRequestProcesser invokeProcesser, ILogger <DefaultHttpReportsMiddleware> logger)
 {
     Next            = next;
     _idWorker       = idWorker;
     Logger          = logger;
     RequestBuilder  = requestBuilder;
     InvokeProcesser = invokeProcesser;
     JsonSetting     = jsonSetting;
     Options         = options.Value;
 }
Ejemplo n.º 31
0
 public void It_should_return_the_correct_job_id()
 {
     var s = new IdWorker(1, 1);
     Assert.That(s.WorkerId, Is.EqualTo(1));
 }
Ejemplo n.º 32
0
        public void It_should_roll_over_sequence_id()
        {
            // put a zero in the low bit so we can detect overflow from the sequence
            const int workerId = 4;
            const int datacenterId = 4;
            var worker = new IdWorker(workerId, datacenterId);
            const int startSequence = 0xFFFFFF-20;
            const int endSequence = 0xFFFFFF+20;
            worker.Sequence = startSequence;

            for (var i = startSequence; i <= endSequence; i++)
            {
                var id = worker.NextId();
                var actual = (id & WorkerMask) >> 12;
                Assert.That(actual, Is.EqualTo(workerId));
            } 
        }
Ejemplo n.º 33
0
 public void It_should_properly_mask_timestamp()
 {
     var worker = new IdWorker(31, 31);
     for (var i = 0; i < 100; i++)
     {
         var t = System.CurrentTimeMillis();
         using (System.StubCurrentTime(t))
         {
             var id = worker.NextId();
             var actual = (((ulong)id & TimestampMask) >> 22);
             var expected = (t - IdWorker.Twepoch);
             Assert.That(expected, Is.EqualTo(actual));   
         }
     }
 }
Ejemplo n.º 34
0
 public void It_should_generate_1_million_ids_quickly()
 {
     var worker = new IdWorker(31, 31);
     var t = System.CurrentTimeMillis();
     for (int i = 0; i < 1000000; i++)
     {
         var id = worker.NextId();
     }
     var t2 = System.CurrentTimeMillis();
     Console.WriteLine("generated 1000000 ids in {0} ms, or {1} ids/second", t2 - t, 1000000000.0/(t2-t));
 }
Ejemplo n.º 35
0
 public void It_should_generate_increasing_ids()
 {
     var worker = new IdWorker(1, 1);
     var lastId = 0L;
     for (var i = 0; i < 100; i++)
     {
         var id = worker.NextId();
         Assert.That(id, Is.GreaterThan(lastId)); 
         lastId = id;
     }
 }
Ejemplo n.º 36
0
 public void It_should_generate_only_unique_ids()
 {
     var worker = new IdWorker(31, 31);
     var set = new HashSet<long>();
     const int N = 2000000;
     for (var i = 0; i < N; i++)
     {
         var id = worker.NextId();
         if (set.Contains(id))
         {
             Console.WriteLine("Found duplicate : {0}", id);
         }
         else
         {
             set.Add(id);
         }
     }
     Assert.That(set.Count, Is.EqualTo(N));
 }
Ejemplo n.º 37
0
 public void It_should_generate_ids_over_50_billion()
 {
     var worker = new IdWorker(0, 0);
     var id = worker.NextId();
     Assert.That(id, Is.GreaterThan(50000000000L));
 }
Ejemplo n.º 38
0
 public void It_should_generate_an_id()
 {
     var worker = new IdWorker(1, 1);
     var v = worker.NextId();
     Assert.That(v, Is.GreaterThan(0));
 }
Ejemplo n.º 39
0
 public void It_should_return_the_datacenter_id()
 {
     var s = new IdWorker(1, 1);
     Assert.That(s.DatacenterId, Is.EqualTo(1));
 }
Ejemplo n.º 40
0
 public void It_should_properly_mask_the_datacenter_id()
 {
     const int workerId = 0x1F;
     const int datacenterId = 0;
     var worker = new IdWorker(workerId, datacenterId);
     for (var i = 0; i < 1000; i++)
     {
         var id = worker.NextId();
         var expected = (id & DatacenterMask) >> 17;
         Assert.That(datacenterId, Is.EqualTo(expected));
     }
 }