//处理任务 public void StartToQueueProcess(ICommonRedisClient redisClient) { var queueName = redisClient.PopItemWithLowestScoreFromSortedSet(CONST_WAIT_PROCESS_QUEUES); bool needProcess = false; if (!string.IsNullOrWhiteSpace(queueName)) { string lockKey = $"{CONST_IN_PROCESSING_QUEUES}-{queueName}-lockKey"; using (var dl = redisClient.AcquireLock(lockKey, new TimeSpan(0, 0, 0, 10))) { if (dl != null) { DateTime inProcessTime = DateTime.MinValue; var strInprocessTime = redisClient.GetValueFromHash(CONST_IN_PROCESSING_QUEUES, queueName); if (!string.IsNullOrWhiteSpace(strInprocessTime)) { DateTime.TryParse(strInprocessTime, out inProcessTime); } if (inProcessTime == DateTime.MinValue) { redisClient.SetEntryInHash(CONST_IN_PROCESSING_QUEUES, queueName, DateTime.Now.ToString(BaseSystemInfo.DateFormat)); needProcess = true; } else { if (inProcessTime.AddMinutes(5) < DateTime.Now) { redisClient.RemoveEntryFromHash(CONST_IN_PROCESSING_QUEUES, queueName); } } } else { LogUtilities.WriteLine("获取锁失败"); } } } if (needProcess) { if (!string.IsNullOrEmpty(queueName)) { LogUtilities.WriteLine($"处理的任务队列是{queueName}"); redisClient.Remove(queueName); } } }
public override bool Work(int index) { try { switch (index) { //0 号线程 主进程是扫描任务加入到等待队列,不是主进程就处理任务。 case 0: { var mainProcessKey = "MainSevice-Process"; string lockKey = $"{mainProcessKey}-lock"; var isMain = false; //第一次进入时,判断当前是否存在主。 bool existMain = false; using (var dl = TestRedis.TestClient.AcquireLock(lockKey, new TimeSpan(0, 0, 0, 0, 1000))) { if (dl != null) { existMain = TestRedis.TestClient.ContainsKey(mainProcessKey); if (existMain) { KeyValueObject <string, DateTime> kvpMainFlag = TestRedis.TestClient.Get <KeyValueObject <string, DateTime> >(mainProcessKey); if (kvpMainFlag.Key.Equals(ServiceName)) { isMain = true; TestRedis.TestClient.Set(mainProcessKey, new KeyValueObject <string, DateTime>(ServiceName, DateTime.Now)); } else { if (kvpMainFlag.Value.AddMinutes(5d) < DateTime.Now) { isMain = true; TestRedis.TestClient.Set(mainProcessKey, new KeyValueObject <string, DateTime>(ServiceName, DateTime.Now)); } } } else { isMain = true; TestRedis.TestClient.Set(mainProcessKey, new KeyValueObject <string, DateTime>(ServiceName, DateTime.Now)); } } else { LogUtilities.WriteLine("获取锁失败!!!"); } } TestQueueService testQueueService = new TestQueueService(); if (isMain) { testQueueService.ScanQueue(); LogUtilities.WriteLog("加入等待队列完毕"); //ScanProcess //加入到等待队列 } else { testQueueService.StartToQueueProcess(TestRedis.TestClient); LogUtilities.WriteLog("处理任务完毕"); //处理任务 } break; } default: { TestQueueService testQueueService = new TestQueueService(); testQueueService.StartToQueueProcess(TestRedis.TestClient); } break; } } catch (Exception ex) { LogUtilities.WriteException(ex); } return(base.Work(index)); }