Beispiel #1
0
        public int Transaction()
        {
            string fromAccID = textBox3.Text;
            string toAccID   = textBox5.Text;
            Double ammount   = textBox6.Text.ToDouble();

            string[] watchFromKeys = { $"account:{textBox3.Text}", "Balance" };
            string[] watchToKeys   = { $"account:{ textBox5.Text}", "Balance" };


            redisClient.Watch(watchFromKeys);
            redisClient.Watch(watchToKeys);
            using (IRedisTransaction trans = redisClient.CreateTransaction())
            {
                Double balanceFrom = GetBalanceInfo(fromAccID);
                Double balanceTo   = GetBalanceInfo(toAccID);

                if (balanceFrom >= ammount)
                {
                    balanceFrom -= ammount;
                    balanceTo   += ammount;
                    trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"account:{fromAccID}", "Balance", balanceFrom.ToString()));
                    trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"account:{toAccID}", "Balance", balanceTo.ToString()));
                    return(trans.Commit() == false ? 0 : 1);    //TODO: limit cycles
                }
                else
                {
                    return(-1);
                }
            }
        }
        /// <inheritdoc />
        public void Add(Guid taskId, ITask task)
        {
            Trace.WriteLine("ENTER: Adding task '{0}' with ID '{1}' ...".FormatInvariant(task, taskId));

            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            string taskIdAsString = RedisConverter.ToString(taskId);

            if (this.serializer.CanDetermineEntityTypeFromContent)
            {
                this.provider.SetHashValue(RedisTaskRepository.TasksHashKey, taskIdAsString, this.serializer.Serialize(task));
            }
            else
            {
                using (IRedisTransaction transaction = this.provider.CreateTransaction())
                {
                    transaction.SetHashValue(RedisTaskRepository.TasksHashKey, taskIdAsString, this.serializer.Serialize(task));
                    transaction.SetHashValue(RedisTaskRepository.TasksHashKey, taskIdAsString + "$Type", RedisConverter.ToString(task.GetType(), true));

                    transaction.Commit();
                }
            }

            Trace.WriteLine("EXIT: Task '{0}' with ID '{1}' added.".FormatInvariant(task, taskId));
        }
        /// <inheritdoc />
        public void Fail(Guid taskId, DateTime timestampUtc, Exception error)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            Trace.WriteLine("ENTER: Record task '{0}' failed with error '{1}' ...".FormatInvariant(taskId, error.Message));

            string taskIdAsString = RedisConverter.ToString(taskId);

            string entityKey = RedisTaskRuntimeInfoRepository.GetEntityKey(taskIdAsString);

            RedisTaskRuntimeInfo taskInfo = this.GetById(taskId, false);

            taskInfo.Status       = TaskStatus.Failed;
            taskInfo.CompletedUtc = timestampUtc;
            taskInfo.Error        = error.ToString();

            byte[] content = this.serializer.Serialize(taskInfo);

            using (IRedisTransaction transaction = this.Provider.CreateTransaction())
            {
                transaction.RemoveKey(entityKey);
                transaction.RemoveFromList(RedisTaskRuntimeInfoRepository.ActiveTasksList, taskIdAsString);
                transaction.AddToList(RedisTaskRuntimeInfoRepository.FailedTasksList, taskIdAsString);
                transaction.SetHashValue(RedisTaskRuntimeInfoRepository.ArchiveTasksHash, taskIdAsString, content);

                transaction.Commit();
            }

            Trace.WriteLine("EXIT: Task '{0}' failed with error '{1}' recorded.".FormatInvariant(taskId, error.Message));
        }
        /// <inheritdoc />
        public void Complete(Guid taskId, DateTime timestampUtc)
        {
            Trace.WriteLine("ENTER: Record task '{0}' completed ...".FormatInvariant(taskId));

            string taskIdAsString = RedisConverter.ToString(taskId);

            string entityKey = RedisTaskRuntimeInfoRepository.GetEntityKey(taskIdAsString);

            RedisTaskRuntimeInfo taskInfo = this.GetById(taskId, false);

            taskInfo.Percentage   = 100;
            taskInfo.Status       = TaskStatus.Success;
            taskInfo.CompletedUtc = timestampUtc;

            byte[] content = this.serializer.Serialize(taskInfo);

            using (IRedisTransaction transaction = this.Provider.CreateTransaction())
            {
                transaction.RemoveKey(entityKey);
                transaction.RemoveFromList(RedisTaskRuntimeInfoRepository.ActiveTasksList, taskIdAsString);
                transaction.SetHashValue(RedisTaskRuntimeInfoRepository.ArchiveTasksHash, taskIdAsString, content);

                transaction.Commit();
            }

            Trace.WriteLine("EXIT: Task '{0}' completed recorded.".FormatInvariant(taskId));
        }
        private void AddOrUpdate(IScheduledTask scheduledTask)
        {
            string taskIdAsString = RedisConverter.ToString(scheduledTask.Id);

            if (this.serializer.CanDetermineEntityTypeFromContent)
            {
                this.provider.SetHashValues(
                    RedisScheduledTaskRepository.ScheduledTasksHashKey,
                    new Dictionary <string, byte[]>()
                {
                    { taskIdAsString + "$Content", this.serializer.Serialize(scheduledTask) },
                    { taskIdAsString + "$RecurrenceDefinition", this.serializer.Serialize(scheduledTask.Schedule) }
                });
            }
            else
            {
                using (IRedisTransaction transaction = this.provider.CreateTransaction())
                {
                    transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$Content", this.serializer.Serialize(scheduledTask));
                    transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$Type", RedisConverter.ToString(scheduledTask.GetType(), false));
                    transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$RecurrenceDefinition", this.serializer.Serialize(scheduledTask.Schedule));
                    transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$RecurrenceDefinition$Type", RedisConverter.ToString(scheduledTask.Schedule.GetType(), false));

                    transaction.Commit();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Commit()
        {
            bool result = _transaction != null && _transaction.Commit();

            _transaction = null;
            return(result);
        }
Beispiel #7
0
        private void OnSwitchTo(object sender, RoutedEventArgs e)
        {
            string newID = thisWindowRedis.Incr(taskID).ToString();

            MenuItem selectMenuItem = sender as MenuItem;

            List <string> newTaskProperities = new List <string>();

            {
                newTaskProperities.Add(MainWindow.myUsername);
                newTaskProperities.Add(((MenuItem)selectMenuItem.Parent).Name);
                newTaskProperities.Add("Waiting");
                newTaskProperities.Add(TimeStyle.ConvertDateTimeInt(thisWindowRedis.GetServerTime().AddHours(8)).ToString());
                newTaskProperities.Add("2");
                newTaskProperities.Add(((Server)serverListView.SelectedItem).ServerID);
                newTaskProperities.Add(selectMenuItem.Tag.ToString());
            }
            for (int j = 0; j < newTaskProperities.Count; j++)
            {
                thisWindowRedis.Set <string>(RedisKeyName.taskPrefix + newID + taskProperities[j], newTaskProperities[j]);
            }
            using (IRedisTransaction IRT = thisWindowRedis.CreateTransaction())
            {
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskList, newID));
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskListCopy, newID));
                IRT.Commit();
            }
        }
Beispiel #8
0
        /// <inheritdoc />
        public void Update(ITaskProcessorRuntimeInfo taskProcessorInfo)
        {
            if (taskProcessorInfo == null)
            {
                throw new ArgumentNullException("taskProcessorInfo");
            }

            Trace.WriteLine("ENTER: Updating {0} ...".FormatInvariant(taskProcessorInfo));

            string entityKey = RedisTaskProcessorRuntimeInfoRepository.GetEntityKey(taskProcessorInfo.TaskProcessorId);

            IReadOnlyDictionary <string, string> values = RedisTaskProcessorRuntimeInfoRepository.Serialize(taskProcessorInfo);

            using (IRedisTransaction transaction = this.provider.CreateTransaction())
            {
                transaction.RemoveKey(entityKey);

                transaction.SetHashValues(entityKey, values);

                if (this.expiration < TimeSpan.MaxValue)
                {
                    transaction.ExpireKeyIn(entityKey, this.expiration);
                }

                transaction.Commit();
            }

            Trace.WriteLine("EXIT: {0} updated.".FormatInvariant(taskProcessorInfo));
        }
        /// <inheritdoc />
        public void Add(Guid taskId, ITaskSummary summary)
        {
            Trace.WriteLine("ENTER: Adding summary '{0}' for task '{1}' ...".FormatInvariant(summary, taskId));

            if (summary == null)
            {
                throw new ArgumentNullException(nameof(summary));
            }

            string taskIdAsString = RedisConverter.ToString(taskId);

            byte[] content = this.serializer.Serialize(summary);

            if (this.serializer.CanDetermineEntityTypeFromContent)
            {
                this.provider.SetHashValue(RedisTaskSummaryRepository.RedisTaskSummaryHashKey, taskIdAsString, content);
            }
            else
            {
                using (IRedisTransaction transaction = this.provider.CreateTransaction())
                {
                    transaction.SetHashValue(RedisTaskSummaryRepository.RedisTaskSummaryHashKey, taskIdAsString, content);
                    transaction.SetHashValue(RedisTaskSummaryRepository.RedisTaskSummaryHashKey, taskIdAsString + "$Type", RedisConverter.ToString(summary.GetType(), false));

                    transaction.Commit();
                }
            }

            Trace.WriteLine("EXIT: Summary '{0}' added for task '{1}'.".FormatInvariant(summary, taskId));
        }
Beispiel #10
0
 private void UseTransaction(IRedisClient client, System.Action <IRedisTransaction> action)
 {
     using (IRedisTransaction transaction = client.CreateTransaction())
     {
         action(transaction);
         transaction.Commit();
     }
 }
Beispiel #11
0
 private Double GetBalanceInfo(string accID, IRedisTransaction trans)
 {
     using (trans)
     {
         string balanceSt = "";
         trans.QueueCommand(redisClient => redisClient.GetValueFromHash($"account:{accID}", "Balance"), x => balanceSt = x);
         trans.Commit();
         Double balance = balanceSt.ToDouble();
         return(balance);
     }
 }
Beispiel #12
0
        public static bool TransactionSet(string key, string value)
        {
            var redisClient = basicRedisClientManager.GetClient();

            using (IRedisTransaction IRT = redisClient.CreateTransaction())
            {
                IRT.QueueCommand(r => r.Set <string>(key, value));
                IRT.QueueCommand(r => r.Increment(key, 1));

                return(IRT.Commit()); // 提交事务
            }
        }
Beispiel #13
0
        /// <inheritdoc />
        public void Delete(Guid taskProcessorId)
        {
            string entityKey = RedisTaskProcessorRuntimeInfoRepository.GetEntityKey(taskProcessorId);

            using (IRedisTransaction transaction = this.provider.CreateTransaction())
            {
                transaction.RemoveFromSet(RedisTaskProcessorRuntimeInfoRepository.EntitySetKey, RedisConverter.ToString(taskProcessorId));

                transaction.RemoveKey(entityKey);

                transaction.Commit();
            }
        }
Beispiel #14
0
        private static void DemoRedisTransaction()
        {
            using (IRedisClient redisClient = new RedisClient())
            {
                const string      key         = "abc";
                IRedisTransaction transaction = redisClient.CreateTransaction();
                transaction.QueueCommand(c => c.Set(key, 1));
                transaction.QueueCommand(c => c.Increment(key, 1));
                transaction.Commit();

                int result = redisClient.Get <int>(key);
                Console.WriteLine($"Result = {result}");
            }
        }
Beispiel #15
0
        private void btnResetRedisPKid_Click(object sender, EventArgs e)
        {
            I_Dblink  I_DBL   = (new DBFactory()).DbLinkSqlMain("");
            Hashtable htInput = new Hashtable();

            htInput.Add("@date", null);
            Hashtable htres = I_DBL.RunProc_CMD("[dbo].[AAA_getTableMaxNum_redis]", "tab", htInput);
            DataSet   ds    = new DataSet();

            if ((bool)htres["return_float"])
            {
                ds = (DataSet)htres["return_ds"];
            }
            else
            {
                ds = null;
            }

            if (ds != null && ds.Tables.Contains("tab") && ds.Tables["tab"].Rows.Count > 0)
            {
                RedisClient RC  = RedisClass.GetRedisClient("OnlyOpenOneCheckRedis");
                string      txt = "TableName       MaxNum       MaxId" + Environment.NewLine + "-------------------------------------" + Environment.NewLine;

                //-------计算有效期截止时间---------------
                DateTime dateStart = DateTime.Now;
                //获取当月最后一天的时间
                DateTime dateEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);
                //获取当前时间与当月最后一天相差的秒数作为键值的生命周期
                TimeSpan ts      = dateEnd.Subtract(dateStart).Duration();
                string   seconds = ts.TotalSeconds.ToString("0");

                using (IRedisTransaction IRT = RC.CreateTransaction())
                {//使用事务提交所有重置键值的操作语句
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        txt += dr["tname"].ToString() + "       " + dr["maxnum"].ToString() + "       " + dr["maxid"].ToString() + Environment.NewLine;
                        string key = "str:TablePK:" + dr["tname"].ToString() + DateTime.Now.ToString("yyyyMM");
                        IRT.QueueCommand(r => r.Set(key, Convert.ToInt32(dr["maxid"].ToString())));
                        IRT.QueueCommand(r => r.ExpireEntryAt(key, dateEnd));
                    }
                    IRT.Commit(); // 提交事务
                }
                //将待处理的表信息显示在界面上
                richTextBox1.Text = txt;
            }
            else
            {
                richTextBox1.Text = "没有需要处理的信息!";
            }
        }
Beispiel #16
0
        /// <summary>
        /// 正常执行事物
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCommit_Click(object sender, EventArgs e)
        {
            using (IRedisTransaction IRT = client.CreateTransaction())
            {
                //设置一个key=key  value=20的数据
                IRT.QueueCommand(r => r.Set("key", 20));
                //然后让该数据++1
                IRT.QueueCommand(r => r.Increment("key", 1));

                IRT.Commit(); // 提交事务
                //最终该变量的值是21
            }
            btnGet_Click(null, null);
        }
Beispiel #17
0
        /// <inheritdoc />
        public void SetMaster(Guid taskProcessorId)
        {
            Trace.WriteLine("ENTER: Setting master task processor ID to '{0}' ...".FormatInvariant(taskProcessorId));

            using (IRedisTransaction transaction = this.provider.CreateTransaction())
            {
                transaction.SetValue(RedisTaskProcessorRuntimeInfoRepository.MasterTaskProcessorIdKey, RedisConverter.ToString(taskProcessorId));

                transaction.ExpireKeyIn(RedisTaskProcessorRuntimeInfoRepository.MasterTaskProcessorIdKey, this.Expiration);

                transaction.Commit();
            }

            Trace.WriteLine("EXIT: Master task processor ID set to '{0}'.".FormatInvariant(taskProcessorId));
        }
        /// <inheritdoc />
        public void Add(ITaskRuntimeInfo taskInfo)
        {
            if (taskInfo == null)
            {
                throw new ArgumentNullException("taskInfo");
            }

            Trace.WriteLine("ENTER: Adding runtime information for task '{0}' of type '{1}' with priority '{2}' in polling queue '{3}' ...".FormatInvariant(taskInfo.TaskId, taskInfo.TaskType, taskInfo.Priority, taskInfo.PollingQueue));

            taskInfo.ValidateForAdd();

            string entityKey = RedisTaskRuntimeInfoRepository.GetEntityKey(taskInfo.TaskId);

            string addToListKey;

            Dictionary <string, string> values = new Dictionary <string, string>()
            {
                { "Id", RedisConverter.ToString(taskInfo.TaskId) },
                { "TaskType", RedisConverter.ToString(taskInfo.TaskType, true) },
                { "SubmittedUtc", RedisConverter.ToString(taskInfo.SubmittedUtc) },
                { "Status", RedisConverter.ToString(taskInfo.Status) }
            };

            if (string.IsNullOrEmpty(taskInfo.PollingQueue))
            {
                values.Add("Priority", RedisConverter.ToString(taskInfo.Priority));

                addToListKey = RedisTaskRuntimeInfoRepository.PendingTasksList;
            }
            else
            {
                values.Add("PollingQueue", taskInfo.PollingQueue);

                addToListKey = RedisTaskRuntimeInfoRepository.GetPollingQueueRedisKey(taskInfo.PollingQueue, TaskStatus.Pending);
            }

            using (IRedisTransaction transaction = this.Provider.CreateTransaction())
            {
                transaction.SetHashValues(entityKey, values);

                transaction.AddToList(addToListKey, RedisConverter.ToString(taskInfo.TaskId));

                transaction.Commit();
            }

            Trace.WriteLine("EXIT: Runtime information for task '{0}' of type '{1}' with priority '{2}' in polling queue '{3}' added.".FormatInvariant(taskInfo.TaskId, taskInfo.TaskType, taskInfo.Priority, taskInfo.PollingQueue));
        }
Beispiel #19
0
        public int Transaction(IRedisNativeClient redis)
        {
            Random rnd = new Random();

            while (redis.Exists($"person:{ID}") == 1)
            {
                ID = Nationality + rnd.Next(99999).ToString();
            }
            string[] watchkeys = { $"person:{ID}", "First_Name", "Last_Name" };
            redisClient.Watch(watchkeys);
            using (IRedisTransaction trans = redisClient.CreateTransaction())
            {
                trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"person:{ID}", "First_Name", first_name));
                trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"person:{ID}", "Last_Name", last_name));
                return(trans.Commit() == false ? 0 : 1);
            }
        }
Beispiel #20
0
 public void Transcation()
 {
     using (IRedisTransaction irt = this.iClient.CreateTransaction())
     {
         try
         {
             irt.QueueCommand(r => r.Set("key", 20));
             irt.QueueCommand(r => r.Increment("key", 1));
             irt.Commit(); // 提交事务
         }
         catch (Exception ex)
         {
             irt.Rollback();
             throw ex;
         }
     }
 }
        static void Main1(string[] args)
        {
            PooledRedisClientManager pooleManager = new PooledRedisClientManager(10, 5, ConfigurationManager.AppSettings["RedisServerIP"].ToString());

            var redisClient = pooleManager.GetClient();

            redisClient.Add("key", 1);
            using (IRedisTransaction IRT = redisClient.CreateTransaction())
            {
                IRT.QueueCommand(r => r.Set("key", 20));
                IRT.QueueCommand(r => r.Increment("key", 1));

                IRT.Commit(); // 提交事务
            }
            Console.WriteLine(redisClient.Get <string>("key"));
            Console.ReadKey();
        }
Beispiel #22
0
        private void btnRoleBack_Click(object sender, EventArgs e)
        {
            //先检测key=key的变量
            client.Watch("key");
            //然后再事物之前修改该变量,
            client.Set("key", "123");
            using (IRedisTransaction IRT = client.CreateTransaction())
            {
                //设置一个key=key  value=20的数据
                IRT.QueueCommand(r => r.Set("key", 20));
                //然后让该数据++1
                IRT.QueueCommand(r => r.Increment("key", 1));

                IRT.Commit(); // 提交事务
                //事物在操作该变量的时候,发现key这个变量已经发生改变了,所以就自动回滚了,值还是之前设置的123
            }
            btnGet_Click(null, null);
        }
Beispiel #23
0
 private void SetBalanceInfo(string accID)
 {
     redisClient.Watch($"account:{accID}", "Balance");
     using (IRedisTransaction trans = redisClient.CreateTransaction())
     {
         Double balance = GetBalanceInfo(accID);
         balance += textBox4.Text.ToDouble();
         trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"account:{accID}", "Balance", balance.ToString()));
         if (trans.Commit() == true)
         {
             label11.Text = "Success";
         }
         else
         {
             label11.Text = "Check your account number and try again";
         }
     }
 }
Beispiel #24
0
        public int Transaction(IRedisNativeClient redis)
        {
            Random rnd = new Random();

            while (redis.Exists($"account:{ID}:holder") == 1)
            {
                ID = rnd.Next(99999).ToString();
            }
            //How to update watch in MULTI down below
            redisClient.Watch("account:{ ID}:holder");
            using (IRedisTransaction trans = redisClient.CreateTransaction())
            {
                trans.QueueCommand(redisClient => redisClient.SetEntryInHash($"account:{ID}", "Balance", balance));
                trans.QueueCommand(redisClient => redisClient.Set($"account:{ID}:holder", GetStringBytes(holder)));
                trans.QueueCommand(redisClient => redisClient.AddItemToList($"{holder}_accounts", ID));
                return(trans.Commit() == false ? 0 : 1);
            }
        }
Beispiel #25
0
        /// <inheritdoc />
        public void Push(IUniqueMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (string.IsNullOrEmpty(message.MessageUniqueId))
            {
                throw new ArgumentException("MessageUniqueId is null or empty.".FormatInvariant(message), "message");
            }

            if (this.isDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            Trace.WriteLine("ENTER: Adding message {0}:{1} to list '{2}' ...".FormatInvariant(message.GetType().Name, message.MessageUniqueId, RedisTaskProcessorMessageQueue.MessageQueueListKey));

            byte[] content = this.serializer.Serialize(message);

            if (this.serializer.CanDetermineEntityTypeFromContent)
            {
                this.provider.AddToList(RedisTaskProcessorMessageQueue.MessageQueueListKey, content);
            }
            else
            {
                string messageUniqueId = string.Join("$", message.GetType().Name, message.MessageUniqueId);

                using (IRedisTransaction transaction = this.provider.CreateTransaction())
                {
                    transaction.AddToList(RedisTaskProcessorMessageQueue.MessageQueueListKey, messageUniqueId);

                    transaction.SetHashValue(RedisTaskProcessorMessageQueue.MessageQueueContentKey, messageUniqueId, content);
                    transaction.SetHashValue(RedisTaskProcessorMessageQueue.MessageQueueContentKey, messageUniqueId + "$Type", RedisConverter.ToString(message.GetType(), false));

                    transaction.Commit();
                }
            }

            this.provider.PublishMessage(RedisTaskProcessorMessageQueue.MasterCommandsChannel, string.Empty);

            Trace.WriteLine("EXIT: Message {0}:{1} added to list '{2}'.".FormatInvariant(message.GetType().Name, message.MessageUniqueId, RedisTaskProcessorMessageQueue.MessageQueueListKey));
        }
Beispiel #26
0
        public void RedisLock(IRedisClient redisClient, string key, TimeSpan?timeOut)
        {
            //this.redisClient = redisClient;
            //this.key = key;
            ExecUtils.RetryUntilTrue(delegate
            {
                TimeSpan value    = timeOut ?? new TimeSpan(365, 0, 0, 0);
                DateTime dateTime = DateTime.UtcNow.Add(value);
                string lockString = (dateTime.ToUnixTimeMs() + 1).ToString();
                if (redisClient.SetValueIfNotExists(key, lockString))
                {
                    return(true);
                }
                redisClient.Watch(key);
                long result = -1L;
                string s    = redisClient.Get <string>(key);
                if (!long.TryParse(s, out result))
                {
                    redisClient.UnWatch();
                    return(false);
                }

                if (result <= DateTime.UtcNow.ToUnixTimeMs())
                {
                    using (IRedisTransaction redisTransaction = redisClient.CreateTransaction())
                    {
                        redisTransaction.QueueCommand((IRedisClient r) => r.Set(key, lockString));

                        System.Threading.Thread.Sleep(5 * 1000);

                        bool ok         = redisTransaction.Commit();
                        var lockString2 = redisClient.Get <string>(key);
                        if (lockString2 != lockString)
                        {
                        }

                        return(ok);
                    }
                }
                redisClient.UnWatch();
                return(false);
            }, timeOut);
        }
        public void Commit()
        {
            if (!_transaction.Commit())
            {
                // RedisTransaction.Commit returns false only when
                // WATCH condition has been failed. So, we should
                // re-play the transaction.

                int       replayCount    = 1;
                const int maxReplayCount = 3;

                while (!_transaction.Replay())
                {
                    if (replayCount++ >= maxReplayCount)
                    {
                        throw new RedisException("Transaction commit was failed due to WATCH condition failure. Retry attempts exceeded.");
                    }
                }
            }
        }
Beispiel #28
0
 public void Transcation(Action action)
 {
     using (IRedisTransaction irt = this.iClient.CreateTransaction())
     {
         try
         {
             action.Invoke();
             irt.Commit(); // 提交事务
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             irt.Rollback();
             throw ex;
         }
         finally {
             irt.Dispose();
         }
     }
 }
Beispiel #29
0
        private IUniqueMessage GetByUniqueKey(string messageUniqueKey, bool deleteAfterRead)
        {
            byte[] content             = null;
            string messageTypeAsString = null;

            using (IRedisTransaction transaction = this.provider.CreateTransaction())
            {
                transaction.GetHashBinaryValue(RedisTaskProcessorMessageQueue.MessageQueueContentKey, messageUniqueKey, value => content = value);
                transaction.GetHashTextValue(RedisTaskProcessorMessageQueue.MessageQueueContentKey, messageUniqueKey + "$Type", value => messageTypeAsString = value);

                if (deleteAfterRead)
                {
                    transaction.RemoveFromHash(RedisTaskProcessorMessageQueue.MessageQueueContentKey, messageUniqueKey, messageUniqueKey + "$Type");
                }

                transaction.Commit();
            }

            if (content == null)
            {
                // TODO: Trace warning ...
                return(null);
            }

            if (string.IsNullOrEmpty(messageTypeAsString))
            {
                // TODO: Trace warning ...
                return(null);
            }

            Type messageType = Type.GetType(messageTypeAsString, false);

            if (messageType == null)
            {
                // TODO: Trace warning ...
                return(null);
            }

            return((IUniqueMessage)this.serializer.Deserialize(content, messageType));
        }
Beispiel #30
0
        private void OnMenuItemClick(object sender, RoutedEventArgs e)
        {
            if (((MenuItem)sender).HasItems)
            {
                return;
            }
            if (serverListView.SelectedIndex == -1 || serverListView.SelectedItem == null)
            {
                return;
            }
            MenuItem      selectMenuItem     = sender as MenuItem;
            List <string> newTaskProperities = new List <string>();
            {
                newTaskProperities.Add(MainWindow.myUsername);
                newTaskProperities.Add(selectMenuItem.Name);
                newTaskProperities.Add("Waiting");
                DateTime nowTime = thisWindowRedis.GetServerTime();
                nowTime = nowTime.AddHours(8);
                long   t  = TimeStyle.ConvertDateTimeInt(nowTime);
                string t_ = t.ToString();
                newTaskProperities.Add(t_);

                newTaskProperities.Add("2");
                newTaskProperities.Add(((Server)serverListView.SelectedItem).ServerID);
                newTaskProperities.Add("");
            }

            string newID = thisWindowRedis.Incr(taskID).ToString();

            for (int j = 0; j < newTaskProperities.Count; j++)
            {
                thisWindowRedis.Set <string>(RedisKeyName.taskPrefix + newID + taskProperities[j], newTaskProperities[j]);
            }
            using (IRedisTransaction IRT = thisWindowRedis.CreateTransaction())
            {
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskList, newID));
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskListCopy, newID));
                IRT.Commit();
            }
        }