Example #1
0
 /// <summary>
 /// 消息加入缓存
 /// </summary>
 /// <param name="sendEntity">缓存消息实体</param>
 public static void SetSendData(TerResultEntiy sendEntity)
 {
     try
     {
         var listTer = HashOperator.Get <List <TerResultEntiy> >(RedisServerFlag + sendEntity.IMEI);
         if (listTer != null)
         {
             var singleModel = listTer.SingleOrDefault(p => p.OrderLogID == sendEntity.OrderLogID);
             //如果存在,先删除当前指令
             if (singleModel != null)
             {
                 listTer.Remove(singleModel);
             }
         }
         else
         {
             listTer = new List <TerResultEntiy>();
         }
         listTer.Add(sendEntity);
         HashOperator.Set <List <TerResultEntiy> >(RedisServerFlag + sendEntity.IMEI, listTer);
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #2
0
 static void LoopAddList(int num)
 {
     try
     {
         List <Ter> listTer = new List <Ter>();
         for (int i = 0; i < num; i++)
         {
             for (int k = 0; k < 1; k++)
             {
                 listTer.Add(new Ter()
                 {
                     TerId       = i,
                     TerName     = $"Name_{i}_{k}",
                     IMEI        = i.ToString(),
                     IsOnLine    = true,
                     Lat         = 22.35643434m,
                     Lng         = 112.54754875m,
                     TerTypeCode = "测试设备",
                     data        = Encoding.UTF8.GetBytes($"Name_{i}_{k}")
                 });
             }
             HashOperator.Set <List <Ter> >($"list_{i}", listTer);
             listTer.Clear();
         }
     }
     catch (Exception ex)
     {
         System.Console.WriteLine(ex.Message);
     }
 }
Example #3
0
        /// <summary>
        ///插入数据
        /// </summary>
        /// <param name="num"></param>
        static void LoopAddKey(int num)
        {
            Random r = new Random();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < num; i++)
            {
                for (int k = 0; k < 5; k++)
                {
                    HashOperator.Set <Ter>(string.Format("key_{0}_{1}", i, k), new Ter()
                    {
                        TerId       = i,
                        TerName     = $"Name_{i}",
                        IMEI        = i.ToString(),
                        IsOnLine    = true,
                        Lat         = 22.35643434m,
                        Lng         = 112.54754875m,
                        TerTypeCode = "测试设备",
                        CreateTime  = DateTime.Now.ToString("yyyyMMdd HHmmss"),
                        ExpireTime  = DateTime.Now.AddSeconds(expireTime).ToString("yyyyMMdd HHmmss"),
                        number      = 1
                    });
                }
            }
            sw.Stop();
            System.Console.WriteLine("总耗时:" + sw.ElapsedMilliseconds);
        }
Example #4
0
 /// <summary>
 /// 移除缓存数据
 /// </summary>
 /// <param name="sendEntity">缓存消息实体</param>
 /// <returns></returns>
 public static void RemoveSendData(TerResultEntiy sendEntity)
 {
     try
     {
         var listTer = HashOperator.Get <List <TerResultEntiy> >(RedisServerFlag + sendEntity.IMEI);
         if (listTer != null)
         {
             //仅剩下一条数据,移除整个key
             if (listTer.Count == 1)
             {
                 HashOperator.Remove(RedisServerFlag + sendEntity.IMEI);
             }
             else
             {
                 //移除指定指令数据
                 var singleModel = listTer.SingleOrDefault(p => p.OrderLogID == sendEntity.OrderLogID);
                 if (singleModel != null)
                 {
                     listTer.Remove(singleModel);
                     HashOperator.Set <List <TerResultEntiy> >(RedisServerFlag + sendEntity.IMEI, listTer);
                 }
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #5
0
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main(string[] args)
        {
            HashOperator hashOperator = new HashOperator();

            hashOperator.Set("test", "name", "大壮他哥");
            Console.WriteLine(hashOperator.Get <string>("test", "name"));
            Console.ReadKey();
        }
        /// <summary>
        /// 移除hash中的某值
        /// </summary>
        public static bool RemoveHashKey(string hashId, string key)
        {
            HashOperator operators = new HashOperator();
            bool         results   = operators.Remove(hashId, key);

            operators.Dispose();
            return(results);
        }
        /// <summary>
        /// 判断某个数据是否已经被缓存
        /// </summary>
        public static bool ExistKeyHash(string hashId, string key)
        {
            HashOperator operators = new HashOperator();
            bool         results   = operators.Exist <string>(hashId, key);

            operators.Dispose();
            return(results);
        }
        public static bool SetCacheKeyHash(string hashid, string Key, string Value, DateTime expiretime)
        {
            HashOperator operators = new HashOperator();
            bool         results   = operators.Set <string>(hashid, Key, Value);

            operators.Dispose();
            return(results);
        }
Example #9
0
        public void InitRedis()
        {
            //获取Redis操作接口
            Redis = RedisManager.GetClient();
            //Hash表操作
            operators = new HashOperator();

            Redis.Password = "******";
        }
Example #10
0
        /// <summary>
        /// 队列弹入数据
        /// </summary>
        /// <param name="loops"></param>
        static void Push(int loops)
        {
            string jsonStr = "{\"Msg\":\"ss\",\"CreateDateTime\":\"2018-05-15 15:20:30\"}";

            for (int i = 0; i < loops; i++)
            {
                HashOperator.PushString("list_pop", jsonStr);
            }
        }
Example #11
0
 /// <summary>
 /// 读取缓存数据
 /// </summary>
 /// <param name="IMEI">IMEI号</param>
 /// <returns>null or list</returns>
 public static List <TerResultEntiy> GetSendData(string IMEI)
 {
     try
     {
         return(HashOperator.Get <List <TerResultEntiy> >(RedisServerFlag + IMEI));
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #12
0
        /// <summary>
        /// HashSet
        /// </summary>
        public static void HashSet()
        {
            HashOperator.Set("hash_1", "name", "xxx");
            HashOperator.Set("hash_1", "age", "20");
            HashOperator.Set("hash_1", "set", "男");

            List <string> hashListValue = HashOperator.GetHashValues("hash_1");

            for (int i = 0; i < hashListValue.Count; i++)
            {
                System.Console.WriteLine(hashListValue[i]);
            }
            System.Console.WriteLine(HashOperator.GetHashValues("hash_2").Count);
        }
Example #13
0
        /// <summary>
        /// 队列弹出数据
        /// </summary>
        /// <param name="loops"></param>
        static void Pop(object loops)
        {
            int num = Convert.ToInt32(loops);

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < num; i++)
            {
                HashOperator.PopString("redis_queue");
            }
            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;

            System.Console.WriteLine("pop总耗时:" + ts2.TotalMilliseconds);
        }
Example #14
0
        /// <summary>
        ///插入数据
        /// </summary>
        /// <param name="num"></param>
        static void LoopGetKey(int num)
        {
            Random r = new Random();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            for (int i = 0; i < num; i++)
            {
                for (int k = 0; k < 5; k++)
                {
                    HashOperator.Get <Ter>(string.Format("key_{0}_{1}", i, k));
                }
            }
            sw.Stop();
            System.Console.WriteLine("总耗时:" + sw.ElapsedMilliseconds);
        }
Example #15
0
        public override void Execute()
        {
            //var currentKey = Console.ReadKey(false);
            //var cmd = currentKey.Key;
            //var txt = currentKey.ToString();

            //var currentCmd = AllKeysDictionary.Find(cmd);

            string password = Console.ReadLine();
            var    newHash  = HashOperator.CreateHash(password);
            var    area     = (MainMenuArea)PreviousArea;

            area.Hash = newHash;

            //_previousArea.Redraw();
        }
Example #16
0
        static void GetKeyAsync(int num)
        {
            LimitedConcurrencyLevelTaskScheduler scheduler = new LimitedConcurrencyLevelTaskScheduler(100);
            List <Task> tasks = new List <Task>();
            // Create a TaskFactory and pass it our custom scheduler.
            TaskFactory factory = new TaskFactory(scheduler);

            factory.StartNew(() =>
            {
                int maxWorkerThreads, maxCompletionPortThreads;
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads);
                System.Console.WriteLine($"maxworkerThreads:{maxWorkerThreads},maxCompletionPortThreads:{maxCompletionPortThreads}");
                while (true)
                {
                    int workerThreads = 0, completionPortThreads = 0;
                    ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
                    System.Console.WriteLine($"workerThreads:{workerThreads},completionPortThreads:{completionPortThreads}");
                    Thread.Sleep(200);
                }
            });

            for (int i = 0; i < num; i++)
            {
                for (int k = 0; k < 5; k++)
                {
                    Asyncparams asyncparams = new Asyncparams();
                    asyncparams.BeginIndex = i;
                    asyncparams.EndIndex   = k;
                    Task task = factory.StartNew((n) =>
                    {
                        try
                        {
                            HashOperator.Get <Ter>(string.Format("key_{0}_{1}", asyncparams.BeginIndex, asyncparams.EndIndex));
                            //Thread.Sleep(2);
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                        }
                    }, asyncparams);
                    tasks.Add(task);
                }
            }
            Task.WaitAll(tasks.ToArray());
        }
Example #17
0
 /// <summary>
 /// 读取数据
 /// </summary>
 static void Woker(object obj)
 {
     System.Console.WriteLine("woker thread begin");
     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
     sw.Start();
     #region 查询所有
     for (int i = 0; i < number; i++)
     {
         for (int k = 0; k < 5; k++)
         {
             System.Console.WriteLine(HashOperator.Get <string>(string.Format("key_{0}_{1}", i, k)));
         }
     }
     #endregion
     sw.Stop();
     TimeSpan ts2 = sw.Elapsed;
     System.Console.WriteLine("总耗时:" + ts2.TotalMilliseconds);
 }
Example #18
0
        /// <summary>
        /// 总结:同时操作一个key,是不安全的
        /// </summary>
        static void RunTask()
        {
            int taskNums = 20;

            Task[] tasksArray = new Task[taskNums];
            for (int i = 0; i < taskNums; i++)
            {
                tasksArray[i] = Task.Factory.StartNew(() =>
                {
                    List <Ter> listTer = HashOperator.Get <List <Ter> >($"list_1");
                    if (listTer.Count > 0)
                    {
                        listTer[0].number++;
                    }
                    System.Console.WriteLine(listTer[0].number);
                    HashOperator.Set <List <Ter> >($"list_1", listTer);
                });
            }
            Task.WaitAll(tasksArray);
        }
Example #19
0
 static void LoopGetKeyList(int num)
 {
     try
     {
         System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
         sw.Start();
         for (int i = 0; i < num; i++)
         {
             HashOperator.Get <List <Ter> >($"list_{i}");
         }
         //测试byte数据返回
         System.Console.WriteLine(Encoding.UTF8.GetString(HashOperator.Get <List <Ter> >($"list_1")[0].data));
         sw.Stop();
         TimeSpan ts2 = sw.Elapsed;
         System.Console.WriteLine("总耗时:" + ts2.TotalMilliseconds);
     }
     catch (Exception ex)
     {
         System.Console.WriteLine(ex.Message);
     }
 }
Example #20
0
        static void AsyncPushData(int num)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            string key = "redis_queue";

            for (int i = 0; i < num; i++)
            {
                HashOperator.PushString(key, JsonHelper.ToJson(new Ter()
                {
                    TerId       = i,
                    TerName     = $"Name_{i}",
                    IMEI        = i.ToString(),
                    IsOnLine    = true,
                    Lat         = 22.35643434m,
                    Lng         = 112.54754875m,
                    TerTypeCode = "测试设备"
                }));
            }
            sw.Stop();
            System.Console.WriteLine("push总耗时:" + sw.Elapsed.TotalMilliseconds);
        }
Example #21
0
        public static void Test()
        {
            try
            {
                //获取Redis操作接口
                IRedisClient Redis = RedisManager.GetClient();
                //Hash表操作
                HashOperator operators = new HashOperator();

                //移除某个缓存数据
                bool isTrue = Redis.Remove("additemtolist");

                //将字符串列表添加到redis
                List <string> storeMembers = new List <string>()
                {
                    "韩梅梅", "李雷", "露西"
                };
                storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));

                //得到指定的key所对应的value集合
                Console.WriteLine("得到指定的key所对应的value集合:");
                var members = Redis.GetAllItemsFromList("additemtolist");
                members.ForEach(s => Console.WriteLine("additemtolist :" + s));
                Console.WriteLine("");

                // 获取指定索引位置数据
                Console.WriteLine("获取指定索引位置数据:");
                var item = Redis.GetItemFromList("additemtolist", 2);
                Console.WriteLine(item);

                Console.WriteLine("");

                //将数据存入Hash表中
                Console.WriteLine("Hash表数据存储:");
                UserInfo userInfos = new UserInfo()
                {
                    UserName = "******", Age = 45
                };
                var    ser     = new ObjectSerializer(); //位于namespace ServiceStack.Redis.Support;
                bool   results = operators.Set <byte[]>("userInfosHash", "userInfos", ser.Serialize(userInfos));
                byte[] infos   = operators.Get <byte[]>("userInfosHash", "userInfos");
                userInfos = ser.Deserialize(infos) as UserInfo;
                Console.WriteLine("name=" + userInfos.UserName + "   age=" + userInfos.Age);

                Console.WriteLine("");

                //object序列化方式存储
                Console.WriteLine("object序列化方式存储:");
                UserInfo uInfo = new UserInfo()
                {
                    UserName = "******", Age = 12
                };
                bool     result    = Redis.Set <byte[]>("uInfo", ser.Serialize(uInfo));
                UserInfo userinfo2 = ser.Deserialize(Redis.Get <byte[]>("uInfo")) as UserInfo;
                Console.WriteLine("name=" + userinfo2.UserName + "   age=" + userinfo2.Age);

                Console.WriteLine("");

                //存储值类型数据
                Console.WriteLine("存储值类型数据:");
                Redis.Set <int>("my_age", 12);//或Redis.Set("my_age", 12);
                int age = Redis.Get <int>("my_age");
                Console.WriteLine("age=" + age);

                Console.WriteLine("");

                //序列化列表数据
                Console.WriteLine("列表数据:");
                List <UserInfo> userinfoList = new List <UserInfo> {
                    new UserInfo {
                        UserName = "******", Age = 1, Id = 1
                    },
                    new UserInfo {
                        UserName = "******", Age = 3, Id = 2
                    },
                };
                Redis.Set <byte[]>("userinfolist_serialize", ser.Serialize(userinfoList));
                List <UserInfo> userList = ser.Deserialize(Redis.Get <byte[]>("userinfolist_serialize")) as List <UserInfo>;
                userList.ForEach(i =>
                {
                    Console.WriteLine("name=" + i.UserName + "   age=" + i.Age);
                });
                //释放内存
                Redis.Dispose();
                operators.Dispose();
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.WriteLine("Please open the redis-server.exe ");
                Console.ReadKey();
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            #region 异步读取数据
            //for (int i = 0; i < 10; i++)
            //{
            //    Thread thread = new Thread(Woker);
            //    thread.Start(number);
            //}

            //for (int i = 0; i < 10; i++)
            //{
            //    Thread thread = new Thread(Pop);
            //    thread.Start(1000);
            //}
            #endregion

            #region 监听事件
            //Task.Run(() =>
            //{
            //    HashOperator.SubscribeExpireNot((channel, msg) => {
            //        var thisKey = msg.Substring(0, msg.IndexOf("$"));
            //        Ter terInfor = HashOperator.Get<Ter>(msg.Substring(0, msg.IndexOf("$")));
            //        if (terInfor!= null)
            //        {
            //            System.Console.WriteLine($"name:{terInfor.TerName},CretateTime:{terInfor.CreateTime},TimeStamp:{terInfor.ExpireTime},number:{terInfor.number}");
            //            if (terInfor.number > 2)
            //            {
            //                HashOperator.Remove(thisKey);
            //            }
            //            else
            //            {
            //                terInfor.number += 1;
            //                terInfor.CreateTime = DateTime.Now.ToString("yyyyMMdd HHmmss");
            //                terInfor.ExpireTime = DateTime.Now.AddSeconds(expireTime).ToString("yyyyMMdd HHmmss");
            //                HashOperator.Set<string>(msg, "", DateTime.Now.AddSeconds(expireTime));
            //                HashOperator.Set<Ter>(thisKey,terInfor);
            //            }
            //        }
            //    });
            //});
            #endregion

            #region 插入数据
            //Task.Run(() =>
            //{
            //    try
            //    {
            //        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //        sw.Start();
            //        LoopAddList(number);

            //        //Push(number);
            //        //LoopAddKey(number);

            //        sw.Stop();
            //        TimeSpan ts2 = sw.Elapsed;
            //        System.Console.WriteLine("总耗时:" + ts2.TotalMilliseconds);
            //    }
            //    catch (Exception ex)
            //    {

            //        System.Console.WriteLine(ex.StackTrace);
            //    }
            //});
            #endregion

            #region 配置文件判断
            if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["MaxIMEINumber"]))
            {
                throw new Exception("imei num config is empty");
            }
            IMEI_NUM = Convert.ToInt32(ConfigurationManager.AppSettings["MaxIMEINumber"]);
            #endregion

            System.Console.WriteLine("******************ts  设置key; tr 删除; tg 获取key ***************************");
            while (true)
            {
                string input = System.Console.ReadLine();
                if (input == "c")
                {
                    System.Console.Clear();
                }
                else if (input == "t")
                {
                    RunTask();
                }
                else if (input == "delete")
                {
                    HashOperator.RemoveByPattern("list_3479*");
                }
                else if (input == "ts")
                {
                    TestBusinessMainSet();
                }
                else if (input == "tg")
                {
                    TestBusinessMainGet();
                }
                else if (input == "tr")
                {
                    TestBusinessMainRemove();
                }
                else if (input == "td")
                {
                    GetRedisData();
                }
                else if (input == "tts")
                {
                    LoopAddKey(number);
                }
                else if (input == "")
                {
                    GetKeyAsync(number);
                }
                else if (input == "hash")
                {
                    HashSet();
                }
                else if (input == "push")
                {
                    AsyncPushData(1000000);
                }
                else if (input == "pop")
                {
                    Pop(1000000);
                }
                else
                {
                    System.Console.WriteLine("输入错误!");
                }
            }
            System.Console.ReadKey();
        }