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);
                }
            }
        }
Beispiel #2
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();
            }
        }
 /// <summary>
 /// 设置Hash中某个字段的值自增
 /// </summary>
 /// <param name="hashId">hashId</param>
 /// <param name="key">键</param>
 /// <param name="increment">增量</param>
 /// <returns></returns>
 public long HashSetIncre(string hashId, string key, int increment)
 {
     if (_transaction != null)
     {
         _transaction.QueueCommand(r => r.IncrementValueInHash(hashId, key, increment));
         return(0);
     }
     else
     {
         return(_client.IncrementValueInHash(hashId, key, increment));
     }
 }
Beispiel #4
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()); // 提交事务
            }
        }
 public TEntity Insert(TEntity entity)
 {
     try
     {
         trans.QueueCommand(c => c.AddItemToList(entity.GetType().Name, new JavaScriptSerializer().Serialize(entity)));
         return(entity);
     }
     catch (Exception ex)
     {
         SystemLogger.SystemLogger.LogException(ex);
         return(null);
     }
 }
Beispiel #6
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 #7
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 #8
0
        private void RemoveFromFetchedList(IRedisTransaction transaction)
        {
            transaction.QueueCommand(x => x.RemoveItemFromList(
                                         String.Format(RedisStorage.Prefix + "queue:{0}:dequeued", Queue),
                                         JobId,
                                         -1));

            transaction.QueueCommand(x => x.RemoveEntryFromHash(
                                         String.Format(RedisStorage.Prefix + "job:{0}", JobId),
                                         "Fetched"));
            transaction.QueueCommand(x => x.RemoveEntryFromHash(
                                         String.Format(RedisStorage.Prefix + "job:{0}", JobId),
                                         "Checked"));
        }
Beispiel #9
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 #10
0
 public static void QueueCommandMap(this IRedisTransaction transaction, Func <IRedisClient, byte[][]> command, Action <IDictionary <string, byte[]> > onSuccessCallback)
 {
     transaction.QueueCommand(command, (multiData) =>
     {
         onSuccessCallback(RedisClientExtensions.MultiByteArrayToDictionary(multiData));
     });
 }
        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 #12
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 #13
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;
         }
     }
 }
Beispiel #14
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 #15
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 #16
0
 private static void TransUpdateEntity(IRedisTransaction trans, string hashId, byte[][] keys, byte[][] values, byte[][] removeKeys)
 {
     if (keys.Length > 0)
     {
         trans.QueueCommand(c =>
         {
             var cli = (RedisClient)c;
             cli.HMSet(hashId, keys, values);
         });
     }
     if (removeKeys.Length > 0)
     {
         trans.QueueCommand(c =>
         {
             var cli = (RedisClient)c;
             cli.HDel(hashId, removeKeys);
         });
     }
 }
Beispiel #17
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 #18
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();
            }
        }
Beispiel #19
0
        public override void ResetItemTimeout(HttpContext context, string id)
        {
            var key = GetSessionIdKey(id);

            using (var client = GetClient())
            {
                IRedisTransaction transaction = client.CreateTransaction();
                using (transaction)
                {
                    transaction.QueueCommand(c => c.ExpireEntryIn(key, TimeSpan.FromMinutes(sessionTimeoutMinutes)));
                }
            }
        }
Beispiel #20
0
        private void OnBtnClick(object sender, RoutedEventArgs e)
        {
            Button thisBtn = (Button)sender;
            int    nowTime = int.Parse(TimeStyle.ConvertDateTimeInt(thisWindowRedis.GetServerTime()).ToString());

            if (preBtn != null && thisBtn == preBtn && (nowTime - preTime < 3))
            {
                string           warningMessage = "此命令与上一条命令重复,请确认是否添加!";
                MessageBoxResult rc             = MessageBox.Show(warningMessage, "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (rc == MessageBoxResult.No)
                {
                    return;
                }
            }
            preBtn  = thisBtn;
            preTime = nowTime;
            string thisID = thisWindowRedis.Incr(taskID).ToString();

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

            {
                thisTaskProperities.Add(MainWindow.myUsername);
                thisTaskProperities.Add((string)thisBtn.Tag);
                thisTaskProperities.Add("Waiting");
                thisTaskProperities.Add(TimeStyle.ConvertDateTimeInt(thisWindowRedis.GetServerTime().AddHours(8)).ToString());
                thisTaskProperities.Add("1");
            }
            for (int i = 0; i < thisTaskProperities.Count; i++)
            {
                thisWindowRedis.Set <string>(RedisKeyName.taskPrefix + thisID + taskProperities[i], thisTaskProperities[i]);
            }
            using (IRedisTransaction IRT = thisWindowRedis.CreateTransaction())
            {
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskList, thisID));
                IRT.QueueCommand(r => r.AddItemToList(RedisKeyName.waitingTaskListCopy, thisID));
                IRT.Commit();
            }
        }
Beispiel #21
0
        private void btnErrorCommit_Click(object sender, EventArgs e)
        {
            try
            {
                using (IRedisTransaction IRT = client.CreateTransaction())
                {
                    //设置一个key=key  value=aaa的数据
                    IRT.QueueCommand(r => r.Set("key", "aaa"));
                    //然后让该数据++1,但是字符串++1是会报错的,所以这一句是没有执行成功的,但是第一句执行成功了
                    IRT.QueueCommand(r => r.Increment("key", 1));

                    IRT.Commit(); // 提交事务
                    //最终该变量的值还是aaa
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                btnGet_Click(null, null);
            }
        }
Beispiel #22
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 #23
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);
        }
Beispiel #24
0
 public void QueueCommand(Func <IRedisClient, bool> command)
 {
     _redisTransaction.QueueCommand(command);
 }
Beispiel #25
0
        private void RemoveFromFetchedList(IRedisTransaction transaction)
        {
            transaction.QueueCommand(x => x.RemoveItemFromList(
                        String.Format(RedisStorage.Prefix + "queue:{0}:dequeued", Queue),
                        JobId,
                        -1));

            transaction.QueueCommand(x => x.RemoveEntryFromHash(
                String.Format(RedisStorage.Prefix + "job:{0}", JobId),
                "Fetched"));
            transaction.QueueCommand(x => x.RemoveEntryFromHash(
                String.Format(RedisStorage.Prefix + "job:{0}", JobId),
                "Checked"));
        }
        /// <summary>
        /// 同步Redis
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonSyncRedis_Click(object sender, EventArgs e)
        {
            string redishost = CtrlHelper.GetText(txtRedisHost);
            int    redisport = 6379;

            int.TryParse(CtrlHelper.GetText(txtRedisPort), out redisport);
            string redispass = CtrlHelper.GetText(txtRedisPassword);
            long   redisdb   = 0;

            long.TryParse(CtrlHelper.GetText(txtRedisDB), out redisdb);

            if (String.IsNullOrWhiteSpace(redishost))
            {
                lblSyncRedis.Text = "HOST 不能为空";
                return;
            }

            try
            {
                var redisClient = new RedisClient(redishost, redisport, redispass, redisdb);
                var str         = redisClient.Get <String>("GAME:ID:IDENTITY");
                System.Console.WriteLine(str);

                //TODO

                string apikey = "";

                string sqlGameInfo = string.Format(@"select [GameID],[GameName],[SDKGameID],[SDKGameKey] from [sdk_GameInfo] where [GameID]={0}", gameid);
                //string sqlIos = string.Format(@"select id,PlatformID,[Version] from [sdk_PlatformVersion] where SystemID=2");
                var gameobj = aideNativeWebFacade.GetDataSetBySql(sqlGameInfo).Tables[0].Rows[0];

                var objgameid = new { id = (string)gameobj["SDKGameID"], apikey = (string)gameobj["SDKGameKey"], gameName = (string)gameobj["GameName"] };
                if (gameobj == null ||
                    string.IsNullOrWhiteSpace(objgameid.id) ||
                    string.IsNullOrWhiteSpace(objgameid.apikey) ||
                    string.IsNullOrWhiteSpace(objgameid.gameName))
                {
                    lblSyncRedis.Text = "数据异常";
                    return;
                }

                string sqlGameChannelProductList                = string.Format(@"SELECT [GameName],[PlatformName],[itemid],[itemcpid],[itemid],[price],[name],[type],[info] FROM [sdk_PlatformConfigProductList] WHERE [GameName]='{0}'", gameid);
                var    gamechannelattrsproductlistobj           = aideNativeWebFacade.GetDataSetBySql(sqlGameChannelProductList).Tables[0].AsEnumerable();
                Dictionary <string, List <object> > productlist = new Dictionary <string, List <object> >();
                foreach (var item in gamechannelattrsproductlistobj)
                {
                    if (!productlist.ContainsKey(item["PlatformName"].ToString()))
                    {
                        productlist.Add(item["PlatformName"].ToString(), new List <object>());
                    }

                    productlist[item["PlatformName"].ToString()].Add(new
                    {
                        itemid   = item["itemid"],
                        itemcpid = item["itemcpid"],
                        price    = item["price"],
                        name     = item["name"],
                        type     = item["type"],
                        info     = item["info"]
                    });
                }

                string sqlGameChannelAttrs = string.Format(@"SELECT [GameName],[PlatformName],[SDKKey],[StringValue] 
                                                              FROM [sdk_PlatformConfig] conf 
                                                              WHERE [GameName]='{0}' 
                                                              AND SDKKey!='SignatureKey'  
                                                              AND [isServer] = 1 
                                                              AND [PlatformName] IN ( 
                                                                SELECT convert(varchar(20),[VersionPlatFromID]) 
                                                                FROM [sdk_GamePlatFromInfo] info 
                                                                WHERE  info.[GameID] =conf.[GameName])
                                                              ORDER BY SDKKey", gameid);
                var    gamechannelattrsobj = aideNativeWebFacade.GetDataSetBySql(sqlGameChannelAttrs).Tables[0].AsEnumerable();
                //string json = JsonConvert.SerializeObject(gamechannelattrsobj);
                Dictionary <string, Dictionary <string, object> > dicattrslist = new Dictionary <string, Dictionary <string, object> >();
                foreach (var item in gamechannelattrsobj)
                {
                    if (!dicattrslist.ContainsKey(item["PlatformName"].ToString()))
                    {
                        dicattrslist.Add(item["PlatformName"].ToString(), new Dictionary <string, object>());
                    }
                    dicattrslist[item["PlatformName"].ToString()].Add(item["SDKKey"].ToString(), item["StringValue"].ToString());
                }

                Dictionary <string, object> jsonoutlist = new Dictionary <string, object>();
                foreach (var item in dicattrslist)
                {
                    item.Value.Add("itemLists", productlist.ContainsKey(item.Key) ? productlist[item.Key] : new List <object>());
                    var jsonout = new { id = item.Value["channel_id"], name = item.Value["sdk_name"], attrs = item.Value };
                    if (!string.IsNullOrWhiteSpace((string)item.Value["channel_id"]))
                    {
                        if (jsonoutlist.ContainsKey("ch" + item.Value["channel_id"]))
                        {
                            throw new ChannelException("渠道编号 " + item.Key + " ChannelID配置重复,请检查");
                        }
                        else
                        {
                            jsonoutlist.Add("ch" + item.Value["channel_id"], jsonout);
                        }
                    }
                }



                using (IRedisTransaction IRT = redisClient.CreateTransaction())
                {
                    //1.更新 'GAME:' + gameid + ':ID' 写入游戏信息,必须有游戏id name gkey
                    string keygameid = "GAME:" + objgameid.id + ":ID";
                    IRT.QueueCommand(r => r.SetEntryInHash(keygameid, "id", objgameid.id));
                    IRT.QueueCommand(r => r.SetEntryInHash(keygameid, "gameName", objgameid.gameName));
                    IRT.QueueCommand(r => r.SetEntryInHash(keygameid, "apikey", objgameid.apikey));

                    //2.更新 'GAME:' + gamename + ':NAME' 写入游戏信息,{id:game.id,name:game.gameName}
                    string keygamename = "GAME:" + objgameid.gameName + ":NAME";
                    IRT.QueueCommand(r => r.SetEntryInHash(keygamename, "id", objgameid.id));
                    IRT.QueueCommand(r => r.SetEntryInHash(keygamename, "name", objgameid.gameName));

                    //3.操作 'GAME:' + gameid + ':CHANNEL' 写入渠道attr信息
                    string keygamechannel = "GAME:" + objgameid.id + ":CHANNEL";
                    foreach (var jsonout in jsonoutlist)
                    {
                        IRT.QueueCommand(r => r.SetEntryInHash(keygamechannel, jsonout.Key, JsonConvert.SerializeObject(jsonout.Value)));
                    }

                    //4.更新 'GAME:' + gameId + ':VERSION' ++
                    string keygameversion = "GAME:" + objgameid.id + ":VERSION";
                    IRT.QueueCommand(r => r.IncrementValueInHash(keygameversion, "version", 1));

                    IRT.Commit(); // 提交事务
                }


                var objgamename = new { id = gameid, name = gamename };



                lblSyncRedis.Text = "同步成功";
            }
            catch (ChannelException ex)
            {
                lblSyncRedis.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                lblSyncRedis.Text = "REDIS 同步出错";
                return;
            }
        }
        public void ExpireJob(string jobId, TimeSpan expireIn)
        {
            _transaction.QueueCommand(x => x.ExpireEntryIn(
                                          String.Format(RedisStorage.Prefix + "job:{0}", jobId),
                                          expireIn));

            _transaction.QueueCommand(x => x.ExpireEntryIn(
                                          String.Format(RedisStorage.Prefix + "job:{0}:history", jobId),
                                          expireIn));

            _transaction.QueueCommand(x => x.ExpireEntryIn(
                                          String.Format(RedisStorage.Prefix + "job:{0}:state", jobId),
                                          expireIn));
        }
Beispiel #28
0
        public static HttpResponseResult SynK3DataToWebSite(Context ctx, SynchroDataType DataType, SynchroDirection Direction, long RedisDbId, IEnumerable <AbsSynchroDataInfo> k3Datas = null, IEnumerable <string> billNos = null, bool SQLFilter = true, bool IsSynchroB2B = false)
        {
            HttpResponseResult               result = null;
            Dictionary <string, string>      dict   = null;
            IEnumerable <AbsSynchroDataInfo> datas  = null;
            List <string>     keys      = null;
            bool              IsSuccess = false;
            IRedisTransaction trans     = null;

            lock (oLock)
            {
                RedisManager redis = new RedisManager(ctx);

                try
                {
                    if (datas != null && datas.Count() > 0)
                    {
                        dict = new Dictionary <string, string>();
                        keys = new List <string>();

                        var group = from d in datas
                                    group d by d.SrcNo into g
                                    select g;

                        if (group != null && group.Count() > 0)
                        {
                            foreach (var g in group)
                            {
                                if (g != null && g.ToList().Count > 0)
                                {
                                    keys.Add(g.Key);
                                    string infoKey = RedisUnreadkey(DataType, Direction) + g.Key;
                                    dict.Add(infoKey, JsonUtils.SerializeObject <IEnumerable <AbsSynchroDataInfo> >(ctx, g.ToList()));
                                }
                            }

                            if (dict.Count > 0)
                            {
                                IRedisClient client = redis.GetClientEx(ctx, RedisDbId);

                                if (IsConnectSuccess(client))
                                {
                                    using (trans = redis.GetClientEx(ctx, RedisDbId).CreateTransaction())
                                    {
                                        trans.QueueCommand(r => r.AddRangeToSet(GetRedisAllKey(DataType, Direction), keys));
                                        trans.QueueCommand(r => r.AddRangeToSet(RedisUnreadkey(DataType, Direction), keys));
                                        trans.QueueCommand(r => r.SetAll(dict));

                                        IsSuccess = trans.Commit();
                                    }
                                    if (IsSuccess)
                                    {
                                        foreach (var d in dict)
                                        {
                                            LogHelper.WriteSynchroDataLog(ctx, DataType, redis.GetClient(ctx, RedisDbId), d.Key, d.Value);
                                        }

                                        LogHelper.WriteSynchroLog_Succ(ctx, DataType, "【" + DataType + "】同步,单据编码" + FormatNumber(datas) + "信息成功同步到Redis");
                                        result         = new HttpResponseResult();
                                        result.Success = true;
                                        result.Message = "【" + DataType + "】同步成功!";
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        result         = new HttpResponseResult();
                        result.Success = false;
                        result.Message = "没有需要同步的数据";

                        LogUtils.WriteSynchroLog(ctx, DataType, result.Message);
                    }
                }
                catch (Exception ex)
                {
                    LogUtils.WriteSynchroLog(ctx, DataType, "【" + DataType + "】同步过程中出现异常,异常信息:" + ex.Message + System.Environment.NewLine + ex.StackTrace);

                    result         = new HttpResponseResult();
                    result.Success = false;
                    result.Message = "【" + DataType + "】出现异常,异常信息:" + System.Environment.NewLine + ex.Message;
                }
            }

            return(result);
        }
Beispiel #29
0
        /// <summary>
        /// 单据审核成功后同步数据到HC网站
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="objects"></param>
        /// <returns></returns>
        public virtual HttpResponseResult OperateAfterAudit(Context ctx, List <DynamicObject> objects = null, IEnumerable <AbsSynchroDataInfo> datas = null, SynchroDataType dataType = default(SynchroDataType))
        {
            IEnumerable <AbsSynchroDataInfo> oDatas = null;
            IRedisClient       client = null;
            IRedisTransaction  trans  = null;
            HttpResponseResult result = null;
            Dictionary <List <string>, Dictionary <string, string> > dicts = null;

            if (objects != null && objects.Count > 0)
            {
                oDatas = GetK3Datas(ctx, objects, ref result);
            }
            if (datas != null && datas.Count() > 0)
            {
                oDatas = datas;
            }

            if (result == null)
            {
                result         = new HttpResponseResult();
                result.Success = true;
            }

            SqlCommand comm = null;
            bool       flag = true;

            try
            {
                if (oDatas != null && oDatas.Count() > 0)
                {
                    int    count = 0;
                    string sql   = GetExecuteUpdateSql(ctx, oDatas.ToList());

                    comm = UpdateBillInfos(ctx, oDatas.ToList(), sql, ref result);

                    if (comm != null)
                    {
                        count = comm.ExecuteNonQuery();
                    }

                    dicts = GetSynchroData(ctx, oDatas, dataType);

                    if (dicts != null && dicts.Count > 0)
                    {
                        RedisManager manager = new RedisManager(ctx);
                        client = manager.GetClientEx(ctx, GetDBID(ctx));
                        trans  = client.CreateTransaction();

                        foreach (var kv in dicts)
                        {
                            trans.QueueCommand(r => r.SetAll(kv.Value));

                            if (dataType == default(SynchroDataType))
                            {
                                trans.QueueCommand(r => r.AddRangeToSet(RedisKeyUtils.GetRedisSetKey(this.DataType, this.Direction)["allKey"], kv.Key));
                                trans.QueueCommand(r => r.AddRangeToSet(RedisKeyUtils.GetRedisSetKey(this.DataType, this.Direction)["unreadKey"], kv.Key));
                            }
                            else
                            {
                                trans.QueueCommand(r => r.AddRangeToSet(RedisKeyUtils.GetRedisSetKey(dataType, this.Direction)["allKey"], kv.Key));
                                trans.QueueCommand(r => r.AddRangeToSet(RedisKeyUtils.GetRedisSetKey(dataType, this.Direction)["unreadKey"], kv.Key));
                            }
                        }
                    }
                    else
                    {
                        result.Success = result.Success && true;
                    }


                    if (count > 0)
                    {
                        if (comm != null)
                        {
                            try
                            {
                                comm.Transaction.Commit();
                                flag = true;
                            }
                            catch (Exception ex)
                            {
                                flag            = false;
                                result.Success  = result.Success && false;
                                result.Message += ex.Message + Environment.NewLine + ex.StackTrace;
                                LogUtils.WriteSynchroLog(ctx, this.DataType, result.Message);
                            }
                        }
                    }
                    if (trans != null)
                    {
                        flag = trans.Commit();
                    }


                    if (!flag)
                    {
                        if (trans != null)
                        {
                            trans.Rollback();
                        }
                        if (comm != null)
                        {
                            if (comm.Transaction != null)
                            {
                                comm.Transaction.Rollback();
                            }
                        }
                        result.Success  = result.Success && false;
                        result.Message += string.Format("【{0}】单据编码【{1}】数据更新和同步到HC网站失败!", dataType == SynchroDataType.None ? DataType : dataType, string.Join(",", oDatas.Select(o => o.SrcNo).ToList()));
                        LogUtils.WriteSynchroLog(ctx, dataType == SynchroDataType.None ? DataType : dataType, result.Message);
                    }
                    else
                    {
                        foreach (var kv in dicts)
                        {
                            if (kv.Value != null && kv.Value.Count > 0)
                            {
                                LogHelper.WriteSynchroDataLog(ctx, this.DataType, client, kv.Value, true);
                            }
                        }

                        result.Success  = result.Success && true;
                        result.Message += string.Format("【{0}】单据编码【{1}】数据更新和同步到HC网站成功!", dataType == SynchroDataType.None ? DataType : dataType, string.Join(",", oDatas.Select(o => o.SrcNo).ToList()));
                        LogUtils.WriteSynchroLog(ctx, dataType == SynchroDataType.None ? DataType : dataType, result.Message);
                    }
                }
                else
                {
                    result.Success = result.Success && true;
                }
            }
            catch (Exception ex)
            {
                if (result != null)
                {
                    result.Success  = result.Success && false;
                    result.Message += ex.Message + Environment.NewLine + ex.StackTrace;
                    LogUtils.WriteSynchroLog(ctx, this.DataType, result.Message);
                }
                if (trans != null)
                {
                    trans.Rollback();
                }
                if (client != null)
                {
                    client.Dispose();
                }
                if (comm != null)
                {
                    if (comm.Transaction != null)
                    {
                        comm.Transaction.Rollback();
                    }
                }
            }

            finally
            {
                if (trans != null)
                {
                    trans.Dispose();
                }
                if (client != null)
                {
                    client.Dispose();
                }
                if (comm != null)
                {
                    if (comm.Connection != null)
                    {
                        comm.Connection.Close();
                    }
                }
            }

            return(result);
        }
Beispiel #30
0
        /// <summary>
        /// 同步K3数据至HC网站
        /// </summary>
        /// <param name="k3Datas"></param>
        /// <param name="billNos"></param>
        /// <returns></returns>
        public virtual HttpResponseResult SynK3DataToWebSite(IEnumerable <AbsSynchroDataInfo> k3Datas = null, IEnumerable <string> billNos = null, bool SQLFilter = true, SynchroDirection direction = SynchroDirection.Default)
        {
            HttpResponseResult               result = null;
            Dictionary <string, string>      dict   = null;
            IEnumerable <AbsSynchroDataInfo> datas  = null;
            List <string>     SynBillNos            = null;
            bool              IsSuccess             = false;
            IRedisTransaction trans = null;

            lock (oLock)
            {
                if (k3Datas == null)
                {
                    datas = GetK3Datas(billNos, SQLFilter);
                }
                else
                {
                    datas = k3Datas;
                }
                try
                {
                    Dictionary <string, string> redisKeys = RedisKeyUtils.GetRedisSetKey(this.DataType, this.Direction);
                    string allKey    = redisKeys["allKey"];
                    string unreadKey = redisKeys["unreadKey"];

                    Dictionary <string, string> synFailDatas = GetSynchroFailureDatas();
                    List <string> failBillNos  = null;
                    List <string> failInfoKeys = null;

                    trans = RedisClient.CreateTransaction();


                    if (synFailDatas != null && synFailDatas.Count > 0)
                    {
                        failBillNos  = GetSychroFailureBillNos(synFailDatas);
                        failInfoKeys = GetSynchroFailureInfoKeys(synFailDatas);

                        trans.QueueCommand(r => r.AddRangeToSet(allKey, failBillNos));
                        trans.QueueCommand(r => r.AddRangeToSet(unreadKey, failBillNos));
                        trans.QueueCommand(r => r.SetAll(synFailDatas));

                        IsSuccess = trans.Commit();
                        trans.Dispose();

                        if (IsSuccess)
                        {
                            UpdateSynchroDataLog(failInfoKeys);
                        }
                    }
                    if (datas != null && datas.Count() > 0)
                    {
                        dict       = new Dictionary <string, string>();
                        SynBillNos = new List <string>();

                        var group = from d in datas
                                    group d by d.SrcNo into g
                                    select g;

                        if (group != null && group.Count() > 0)
                        {
                            foreach (var g in group)
                            {
                                if (g != null && g.ToList().Count > 0)
                                {
                                    SynBillNos.Add(g.Key);
                                    string infoKey = RedisKeyUtils.GetRedisSetKey(this.DataType, this.Direction)["infoKey"] + g.Key;
                                    dict.Add(infoKey, JsonUtils.SerializeObject <IEnumerable <AbsSynchroDataInfo> >(this.K3CloudContext, g.ToList()));
                                }
                            }

                            if (IsConnectSuccess())
                            {
                                if (dict.Count > 0)
                                {
                                    trans = RedisClient.CreateTransaction();
                                    trans.QueueCommand(r => r.AddRangeToSet(allKey, SynBillNos));
                                    trans.QueueCommand(r => r.AddRangeToSet(unreadKey, SynBillNos));
                                    trans.QueueCommand(r => r.SetAll(dict));

                                    IsSuccess = trans.Commit();
                                    trans.Dispose();

                                    if (IsSuccess)
                                    {
                                        UpdateAfterSynchro(datas, true);
                                        LogHelper.WriteSynchroDataLog(this.K3CloudContext, this.DataType, RedisClient, dict, true);

                                        string msg = "【" + this.DataType + "】同步,单据编码" + FormatNumber(datas) + "信息成功同步到Redis";
                                        LogHelper.WriteSynchroLog_Succ(this.K3CloudContext, this.DataType, msg);

                                        result         = new HttpResponseResult();
                                        result.Success = true;
                                        result.Message = msg;
                                    }
                                    else
                                    {
                                        LogHelper.WriteSynchroDataLog(this.K3CloudContext, this.DataType, RedisClient, dict, false);

                                        string msg = "【" + this.DataType + "】同步,单据编码" + FormatNumber(datas) + "信息同步到Redis失败";
                                        LogUtils.WriteSynchroLog(this.K3CloudContext, this.DataType, msg);

                                        result         = new HttpResponseResult();
                                        result.Success = false;
                                        result.Message = msg;
                                    }
                                }
                            }
                            else
                            {
                                LogHelper.WriteSynchroDataLog(this.K3CloudContext, this.DataType, RedisClient, dict, false);
                            }
                        }
                    }
                    else
                    {
                        result         = new HttpResponseResult();
                        result.Success = false;
                        result.Message = "没有需要同步的数据";

                        LogUtils.WriteSynchroLog(this.K3CloudContext, this.DataType, result.Message);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteSynchroDataLog(this.K3CloudContext, this.DataType, RedisClient, dict, false);
                    string msg = "【" + this.DataType + "】同步过程中出现异常,异常信息:" + ex.Message + System.Environment.NewLine + ex.StackTrace;
                    LogUtils.WriteSynchroLog(this.K3CloudContext, this.DataType, msg);

                    result         = new HttpResponseResult();
                    result.Success = false;
                    result.Message = msg;
                    UpdateAfterSynchro(datas, false);
                }
                finally
                {
                    if (trans != null)
                    {
                        trans.Dispose();
                    }
                }
            }

            return(result);
        }
Beispiel #31
0
 public void TranCommand(Action <IRedisClient> command)
 {
     _tran.QueueCommand(command);
 }