public void Show_all_Categories()
        {
            using (var redisBlogPosts = redisClient.GetTypedClient <BlogPost>())
            {
                var blogPosts = redisBlogPosts.GetAll();

                foreach (var blogPost in blogPosts)
                {
                    blogPost.Categories.ForEach(x =>
                                                redisClient.AddItemToSet("urn:Categories", x));
                }

                var uniqueCategories = redisClient.GetAllItemsFromSet("urn:Categories");
                Debug.WriteLine(uniqueCategories.Dump());

                /* Output:
                 * [
                 *      DocumentDB,
                 *      NoSQL,
                 *      Cluster,
                 *      Cache
                 * ]
                 */
            }
        }
Ejemplo n.º 2
0
        //加入Set
        public static void AddSet(RedisClient client)
        {
            client.AddItemToSet("Set1001", "qhh");
            client.AddItemToSet("Set1001", "qihaohao");
            client.AddItemToSet("Set1001", "qihh");
            var set = client.GetAllItemsFromSet("Set1001");

            foreach (var item in set)
            {
                Console.WriteLine(item);
            }
        }
Ejemplo n.º 3
0
        public void Show_all_Categories()
        {
            var redisBlogPosts = redis.As <BlogPost>();
            var blogPosts      = redisBlogPosts.GetAll();

            foreach (var blogPost in blogPosts)
            {
                blogPost.Categories.ForEach(x =>
                                            redis.AddItemToSet("urn:Categories", x));
            }

            var uniqueCategories = redis.GetAllItemsFromSet("urn:Categories");

            uniqueCategories.PrintDump();
        }
 /// <summary>
 /// 添加Set集合
 /// </summary>
 /// <param name="setId">集合名</param>
 /// <param name="item">集合值</param>
 public void AddItemToSet(string setId, string item)
 {
     using (RedisClient redisclient = new RedisClient(RedisPath, RedisPort, "123456"))
     {
         redisclient.AddItemToSet(setId, item);
     }
 }
Ejemplo n.º 5
0
 public static void AddItemToSet(string setId, string item)
 {
     using (RedisClient client = GetClient())
     {
         client.AddItemToSet(setId, item);
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// 添加一条数据到某set集合
 /// </summary>
 /// <param name="setName"></param>
 /// <param name="value"></param>
 public static void AddItemToSet(string setName, string value)
 {
     using (RedisClient client = new RedisClient(redisAddress, 6379))
     {
         client.AddItemToSet(setName.ToString(), value);
     }
 }
Ejemplo n.º 7
0
        private static void SetDemo()
        {
            using (
                var client =
                    new RedisClient(
                        "Qg7EG3uqYBDZBLMPdjkWblKNRhjCb7e9Lo60RJbTHd8=@customer-C.redis.cache.windows.net?ssl=true"))
            {
                const string key = "urn:Set:Customer";
                client.AddRangeToSet(key, new List <string> {
                    "abc", "cde", "def"
                });
                client.AddRangeToSet(key, new List <string> {
                    "abc", "cdsae", "def"
                });
                client.AddItemToSet(key, "One");
            }

            using (
                var client =
                    new RedisClient(
                        "Qg7EG3uqYBDZBLMPdjkWblKNRhjCb7e9Lo60RJbTHd8=@customer-C.redis.cache.windows.net?ssl=true"))
            {
                const string key   = "urn:Set:Customer";
                var          items = client.GetAllItemsFromSet(key);
                foreach (var item in items)
                {
                    Console.WriteLine(item);
                }
            }

            using (
                var client =
                    new RedisClient(
                        "Qg7EG3uqYBDZBLMPdjkWblKNRhjCb7e9Lo60RJbTHd8=@customer-C.redis.cache.windows.net?ssl=true"))
            {
                Console.ReadKey();
                const string key   = "urn:Set:Customer";
                var          items = client.GetAllItemsFromSet(key);
                foreach (var item in items)
                {
                    client.RemoveItemFromSet(key, item);
                }
            }

            using (
                var client =
                    new RedisClient(
                        "Qg7EG3uqYBDZBLMPdjkWblKNRhjCb7e9Lo60RJbTHd8=@customer-C.redis.cache.windows.net?ssl=true"))
            {
                const string key = "urn:Set:Customer";
                client.AddRangeToSet(key, new List <string> {
                    "abcasd", "cadsdsae", "de12f"
                });
                var items = client.GetAllItemsFromSet(key);
                foreach (var item in items)
                {
                    Console.WriteLine(item);
                }
            }
        }
        /// <summary>
        /// Adds a way to this database.
        /// </summary>
        /// <param name="way"></param>
        public override void AddWay(Way way)
        {
            // save the way in the current redis key.
            string wayKey = way.GetRedisKey();

            _wayTypeClient.SetEntry(wayKey, PrimitiveExtensions.ConvertTo(way));

            // save the way-node relation.
            if (way.Nodes != null)
            {
                foreach (long nodeId in way.Nodes)
                {
                    _redisClient.AddItemToSet(PrimitiveExtensions.BuildNodeWayListRedisKey(nodeId),
                                              way.Id.Value.ToString());
                }
            }
        }
Ejemplo n.º 9
0
 public static void SetAdd(String key, String member)
 {
     using (RedisClient redisClient = new RedisClient(host, port))
     {
         redisClient.AddItemToSet(key, member);
         redisClient.Dispose();
     }
 }
Ejemplo n.º 10
0
        private static void TestSet()
        {
            using (var client = new RedisClient("127.0.0.1", 6379))
            {
                client.AddItemToSet("HQF.Tutorial.Redis:A", "B");
                client.AddItemToSet("HQF.Tutorial.Redis:A", "C");
                client.AddItemToSet("HQF.Tutorial.Redis:A", "D");
                client.AddItemToSet("HQF.Tutorial.Redis:A", "E");
                client.AddItemToSet("HQF.Tutorial.Redis:A", "F");

                client.AddItemToSet("HQF.Tutorial.Redis:B", "C");
                client.AddItemToSet("HQF.Tutorial.Redis:B", "F");

                //求差集
                Console.WriteLine("A,B集合差集");
                client.GetDifferencesFromSet("HQF.Tutorial.Redis:A", "HQF.Tutorial.Redis:B").ToList <string>().ForEach(e => Console.Write(e + ","));

                //求集合交集
                Console.WriteLine("\nA,B集合交集");
                client.GetIntersectFromSets(new string[] { "HQF.Tutorial.Redis:A", "HQF.Tutorial.Redis:B" }).ToList <string>().ForEach(e => Console.Write(e + ","));

                //求集合并集
                Console.WriteLine("\nA,B集合并集");
                client.GetUnionFromSets(new string[] { "HQF.Tutorial.Redis:A", "HQF.Tutorial.Redis:B" }).ToList <string>().ForEach(e => Console.Write(e + ","));
            }
        }
Ejemplo n.º 11
0
        private void SimularElMovimientoDeUsuariosEnLinea()
        {
            using (IRedisClient client = new RedisClient())
            {
                Enumerable.Range(1, 10000).ForEach(num => client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-4))), num.ToString()));
                Enumerable.Range(10001, 20000).ForEach(num => client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-3))), num.ToString()));
                Enumerable.Range(20001, 30000).ForEach(num => client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-2))), num.ToString()));
                Enumerable.Range(30001, 40000).ForEach(num => client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-1))), num.ToString()));

                client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-4))), "1");
                client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-3))), "2");
                client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-2))), "3");
                client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now.AddMinutes(-1))), "4");
                client.AddItemToSet(string.Format("userOnline:{0}", DiffWithUnixTime(DateTime.Now)), "1");
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// <![CDATA[保存字符串到redis set]]>
        /// </summary>
        static void SaveStringToRedisSet()
        {
            //1>redis客户端
            using (RedisClient redisClient = (RedisClient)GetRedisClient())
            {
                //set集
                redisClient.Store <string>("_stringKey");
                redisClient.AddItemToSet("_setId", "lichaoqiang");

                redisClient.Save();
            }
        }
Ejemplo n.º 13
0
        //它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
        private static void AddSet(RedisClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            client.AddItemToSet("Set1001", "A");
            client.AddItemToSet("Set1001", "B");
            client.AddItemToSet("Set1001", "C");
            client.AddItemToSet("Set1001", "D");
            var hastset1 = client.GetAllItemsFromSet("Set1001");

            foreach (var item in hastset1)
            {
                Console.WriteLine("Set无序集合Value:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "K");
            client.AddItemToSet("Set1002", "C");
            client.AddItemToSet("Set1002", "A");
            client.AddItemToSet("Set1002", "J");
            var hastset2 = client.GetAllItemsFromSet("Set1002");

            foreach (var item in hastset2)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            var hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });

            foreach (var item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            var hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });

            foreach (var item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            var hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]

            foreach (var item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }
        }
        public void Show_all_Categories()
        {
            var redisBlogPosts = redis.As <BlogPost>();
            var blogPosts      = redisBlogPosts.GetAll();

            foreach (var blogPost in blogPosts)
            {
                blogPost.Categories.ForEach(x =>
                                            redis.AddItemToSet("urn:Categories", x));
            }

            var uniqueCategories = redis.GetAllItemsFromSet("urn:Categories");

            uniqueCategories.PrintDump();

            /* Output:
             * [
             *  DocumentDB,
             *  NoSQL,
             *  Cluster,
             *  Cache
             * ]
             */
        }
Ejemplo n.º 15
0
        public void ApplyEffect(bool toPlayer1, string effect)
        {
            string player;

            if (toPlayer1)
            {
                player = "player1Effects";
            }
            else
            {
                player = "player2Effects";
            }

            redis.AddItemToSet(player, effect);
        }
Ejemplo n.º 16
0
        //合集
        public static void Union(RedisClient client)
        {
            client.AddItemToSet("Set8001", "A");
            client.AddItemToSet("Set8001", "B");
            client.AddItemToSet("Set8001", "C");
            client.AddItemToSet("Set8001", "D");


            client.AddItemToSet("Set8002", "E");
            client.AddItemToSet("Set8002", "F");
            client.AddItemToSet("Set8002", "G");
            client.AddItemToSet("Set8002", "D");
            var setunion = client.GetUnionFromSets("Set8001", "Set8002");

            foreach (var item in setunion)
            {
                Console.WriteLine(item);
            }
        }
        public void AddToSet(string key, string member)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key");
            }

            if (member == null)
            {
                throw new ArgumentNullException("member");
            }

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

            this.operation.QueueCommand(client => client.AddItemToSet(key, member));

            this.IsEmpty = false;
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 向集合中添加数据
 /// </summary>
 /// <param name="item"></param>
 /// <param name="set"></param>
 public static void GetItemToSet(string set, string item)
 {
     redisClient.AddItemToSet(set, item);
 }
Ejemplo n.º 19
0
 private void button21_Click(object sender, EventArgs e)
 {
     client.AddItemToSet("set:name", DateTime.Now.ToLongTimeString());
     client.AddItemToSet("set:name", "set1");
 }
Ejemplo n.º 20
0
 /// <summary>
 /// key集合中添加value值
 /// </summary>
 public void Add(string key, string value)
 {
     RedisClient.AddItemToSet(key, value);
 }
Ejemplo n.º 21
0
        //增加
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                GetdbClient(out RedisClient dbclient);

                string username    = "******";
                string personality = "brave";
                string external    = "cute";


                int w1 = 75;
                int w2 = 88;
                dbclient.Set <int>("w1", w1);
                dbclient.Set <int>("w2", w2);


                //添加string类型
                dbclient.Set <string>("username", username);
                dbclient.Set <string>("personality", personality);
                dbclient.Set <string>("external", external);


                // 添加Hash类型
                string title = "pig peiqi";
                string price = "12.5";
                dbclient.SetEntryInHash("books", "title", title);
                dbclient.SetEntryInHash("books", "price", price);

                //添加list队列类型
                string num1 = "12";
                string num2 = "34";
                dbclient.EnqueueItemOnList("queue", num1);
                dbclient.EnqueueItemOnList("queue", num2);

                //添加list栈类型
                dbclient.PushItemToList("stack", num1);
                dbclient.PushItemToList("stack", num2);

                //添加set类型
                dbclient.AddItemToSet("a", "aaaa1");
                dbclient.AddItemToSet("a", "aaaa2");
                dbclient.AddItemToSet("a", "aaaa3");

                //添加Sorted Set类型(在set的基础上增加了一个顺序的属性)
                dbclient.AddItemToSortedSet("s", "a");
                dbclient.AddItemToSortedSet("s", "b");
                dbclient.AddItemToSortedSet("s", "c");
                dbclient.AddItemToSortedSet("s", "abc");
                dbclient.AddItemToSortedSet("s", "defg");


                var exist = dbclient.Exists("username");
                if (exist == 1)
                {
                    Response.Write("<script>alert('添加成功!')</script>");
                }
                else
                {
                    Response.Write("<script>alert('添加失败!')</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("添加失败!" + ex.Message);
            }
        }
Ejemplo n.º 22
0
 public void AddItemToSet(string setId, string item)
 {
     redisClient.AddItemToSet(setId, item);
 }
Ejemplo n.º 23
0
        public void oceni(string isbn, int ocena, string user)
        {
            if (redis.SIsMember(isbn + ":oceneuser", user.ToAsciiBytes()) == 1)
            {
                string pom = redis.Get <string>(isbn + user + ":ocena");
                redis.Set <string>(isbn + user + ":ocena", ocena.ToString());
                int p;
                int.TryParse(pom, out p);


                string oc = redis.Get <string>(isbn + ":ocena");
                Ocena  o  = (Ocena)JsonSerializer.DeserializeFromString(oc, typeof(Ocena));
                if (p == 1)
                {
                    o.jedan--;
                }
                else if (p == 2)
                {
                    o.dva--;
                }
                else if (p == 3)
                {
                    o.tri--;
                }
                else if (p == 4)
                {
                    o.cetiri--;
                }
                else if (p == 5)
                {
                    o.pet--;
                }
                if (ocena == 1)
                {
                    o.jedan++;
                }
                else if (ocena == 2)
                {
                    o.dva++;
                }
                else if (ocena == 3)
                {
                    o.tri++;
                }
                else if (ocena == 4)
                {
                    o.cetiri++;
                }
                else if (ocena == 5)
                {
                    o.pet++;
                }
                double pomm = o.jedan + 2.0 * o.dva + 3.0 * o.tri + 4.0 * o.cetiri + 5.0 * o.pet;
                o.ocena = pomm / o.brojGlasova;
                redis.Set <string>(isbn + ":ocena", o.ToJsonString());

                return;
            }
            redis.Set <string>(isbn + user + ":ocena", ocena.ToString());
            redis.AddItemToSet(isbn + ":oceneuser", user);
            if (redis.Exists(isbn + ":ocena") == 1)
            {
                string oc = redis.Get <string>(isbn + ":ocena");
                Ocena  o  = (Ocena)JsonSerializer.DeserializeFromString(oc, typeof(Ocena));
                o.brojGlasova++;
                if (ocena == 1)
                {
                    o.jedan++;
                }
                else if (ocena == 2)
                {
                    o.dva++;
                }
                else if (ocena == 3)
                {
                    o.tri++;
                }
                else if (ocena == 4)
                {
                    o.cetiri++;
                }
                else if (ocena == 5)
                {
                    o.pet++;
                }
                double pom = o.jedan + 2.0 * o.dva + 3.0 * o.tri + 4.0 * o.cetiri + 5.0 * o.pet;
                o.ocena = pom / o.brojGlasova;
                redis.Set <string>(isbn + ":ocena", o.ToJsonString());
            }
            else
            {
                Ocena o = new Ocena
                {
                    brojGlasova = 1,
                    ISBN        = isbn,
                    jedan       = 0,
                    dva         = 0,
                    tri         = 0,
                    cetiri      = 0,
                    pet         = 0,
                    ocena       = ocena
                };
                if (ocena == 1)
                {
                    o.jedan++;
                }
                else if (ocena == 2)
                {
                    o.dva++;
                }
                else if (ocena == 3)
                {
                    o.tri++;
                }
                else if (ocena == 4)
                {
                    o.cetiri++;
                }
                else if (ocena == 5)
                {
                    o.pet++;
                }
                redis.Set <string>(isbn + ":ocena", o.ToJsonString());
            }
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            //RedisClient redisClient = new RedisClient("192.168.10.9", 6379);
            //redisClient.Db = 0;
            //redisClient.FlushDb();
            //// 连接池方式
            //using (var hash = new DoRedisHash())
            //{
            //    var count = hash.Core.GetAllKeys();
            //    var keys = hash.GetHashKeys("XICAYN");
            //    var r1 = hash.GetHashValues("XICAYN");
            //    var r = hash.GetValueFromHash("XICAYN", "3UB");
            //}


            // 其他普通方式
            ////声明事务
            //using (var tran = RedisManager.GetClient().CreateTransaction())
            //{
            //    try
            //    {
            //        tran.QueueCommand(p =>
            //        {
            //            //操作redis数据命令
            //            DoRedisBase.Core.Set<int>("name", 30);
            //            long i = DoRedisBase.Core.IncrementValueBy("name", 1);
            //        });
            //        //提交事务
            //        tran.Commit();
            //    }
            //    catch
            //    {
            //        //回滚事务
            //        tran.Rollback();
            //    }
            //    ////操作redis数据命令
            //    //RedisManager.GetClient().Set<int>("zlh", 30);
            //    ////声明锁,网页程序可获得锁效果
            //    //using (RedisManager.GetClient().AcquireLock("zlh"))
            //    //{
            //    //    RedisManager.GetClient().Set<int>("zlh", 31);
            //    //    Thread.Sleep(10000);
            //    //}
            //}


            //在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set
            RedisClient client = new RedisClient("127.0.0.1", 6379);

            var db = client.Db;

            client.Db = 1;
            client.Dispose();
            var pwd = client.Password;

            client.FlushDb();

            var data = client.GetHashValues("AATACX");


            client.Set <string>("DB1", "CGDFDFDFDF");

            #region string
            client.Set <string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(3000));
            //while (true)
            //{
            //    if (client.ContainsKey("StringValueTime"))
            //    {
            //        Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get<string>("StringValueTime"), DateTime.Now);
            //        Thread.Sleep(1000);
            //    }
            //    else
            //    {
            //        Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
            //        break;
            //    }
            //}

            client.Set <string>("StringValue", " String和Memcached操作方法差不多");
            Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get <string>("StringValue"));

            Student stud = new Student()
            {
                id = "1001", name = "李四"
            };
            client.Set <Student>("StringEntity", stud);
            Student Get_stud = client.Get <Student>("StringEntity");
            Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
            #endregion

            #region Hash

            client.FlushDb();
            // https://github.com/ServiceStack/ServiceStack.Redis/blob/master/tests/ServiceStack.Redis.Tests/RedisPipelineTests.cs
            #region 批量添加
            var fields     = new[] { "field1", "field2", "field3" };
            var values     = new[] { "1", "2", "3" };
            var fieldBytes = new byte[fields.Length][];
            for (int i = 0; i < fields.Length; ++i)
            {
                fieldBytes[i] = GetBytes(fields[i]);
            }
            var valueBytes = new byte[values.Length][];
            for (int i = 0; i < values.Length; ++i)
            {
                valueBytes[i] = GetBytes(values[i]);
            }

            byte[][] members = null;
            using (var pipeline = client.CreatePipeline())
            {
                pipeline.QueueCommand(r => ((RedisNativeClient)r).HMSet("HashKey", fieldBytes, valueBytes));
                pipeline.QueueCommand(r => ((RedisNativeClient)r).HGetAll("HashKey"), x => members = x);
                pipeline.Flush();
            }


            using (var hash = new DoRedisHash())
            {
                TimeSpan expires = new TimeSpan(0, 0, 0, 20);
                string   hashId  = "hashId001";
                List <KeyValuePair <string, string> > keyValuePairs = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("key", "value")
                };

                byte[][] keys    = new byte[keyValuePairs.Count][];
                byte[][] values1 = new byte[keyValuePairs.Count][];
                for (int index = 0; index < keyValuePairs.Count; ++index)
                {
                    KeyValuePair <string, string> keyValuePair = keyValuePairs[index];
                    keys[index]    = keyValuePair.Key.ToUtf8Bytes();
                    values1[index] = keyValuePair.Value.ToUtf8Bytes();
                }
                ((RedisClient)hash.Core).HMSet(hashId, keys, values1);
                hash.Core.ExpireEntryIn(hashId, expires);
            }



            //client.SetRangeInHash(hashId, keyValuePairs,);

            // 设置key过期
            client.ExpireEntryAt("HashKey", DateTime.Now.AddMinutes(1));
            for (var i = 0; i < members.Length; i += 2)
            {
                var strrBytes = GetString(members[i]);
            }
            #endregion



            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");

            List <string> HaskKey = client.GetHashKeys("HashID");
            foreach (string key in HaskKey)
            {
                Console.WriteLine("HashID--Key:{0}", key);
            }

            List <string> HaskValue = client.GetHashValues("HashID");
            foreach (string value in HaskValue)
            {
                Console.WriteLine("HashID--Value:{0}", value);
            }

            List <string> AllKey = client.GetAllKeys(); //获取所有的key。
            foreach (string Key in AllKey)
            {
                Console.WriteLine("AllKey--Key:{0}", Key);
            }

            byte[] byteArray = Encoding.UTF8.GetBytes("Name");
            var    bytes     = client.HGet("HashID", byteArray);
            var    str       = Encoding.UTF8.GetString(bytes);
            #endregion

            #region List

            /*
             * list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
             * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
             * 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
             * Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
             */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            var q = client.GetListCount("QueueListId");
            for (int i = 0; i < q; i++)
            {
                Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId"));   //出队(队列先进先出)
            }

            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            var p = client.GetListCount("StackListId");
            for (int i = 0; i < p; i++)
            {
                Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId"));   //出栈(栈先进后出)
            }


            #endregion

            #region Set无序集合

            /*
             * 它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
             */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet <string> hastsetA = client.GetAllItemsFromSet("Set1001");
            foreach (string item in hastsetA)
            {
                Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet <string> hastsetB = client.GetAllItemsFromSet("Set1002");
            foreach (string item in hastsetB)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            HashSet <string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            HashSet <string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            HashSet <string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (string item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }

            #endregion

            #region  SetSorted 有序集合

            /*
             * sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
             * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
             */
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List <string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            foreach (string item in listSetSorted)
            {
                Console.WriteLine("SetSorted有序集合{0}", item);
            }
            #endregion
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Redis中set和zset
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            using (IRedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                //清空当前数据库
                client.FlushDb();

                //set也是一个集合,自动去重的一个
                var libai = new User()
                {
                    ID = "01", Name = "李白"
                };
                client.AddItemToSet("setId", JsonConvert.SerializeObject(libai));
                client.AddItemToSet("setId", JsonConvert.SerializeObject(libai));
                client.AddItemToSet("setId", JsonConvert.SerializeObject(libai));

                var dufu = new User()
                {
                    ID = "02", Name = "杜甫"
                };
                client.AddItemToSet("setId", JsonConvert.SerializeObject(dufu));
                WriteLine(client.GetSetCount("setId"));


                WriteLine("******************");
                //批量
                client.AddRangeToSet("setIds", new List <string>()
                {
                    "01", "02", "03", "04", "05"
                });
                WriteLine(client.GetSetCount("setIds"));

                var sets = client.GetAllItemsFromSet("setIds");
                foreach (var item in sets)
                {
                    WriteLine(item);
                }

                WriteLine("******************");

                //随机获取set中的值
                for (int i = 0; i < 10; i++)
                {
                    WriteLine(client.GetRandomItemFromSet("setIds"));
                }

                WriteLine("******************");
                //随机删除,返回结果并删除
                for (int i = 0; i < 3; i++)
                {
                    WriteLine(client.PopItemFromSet("setIds"));
                }

                WriteLine("******************");

                client.AddRangeToSet("ids", new List <string>()
                {
                    "01", "02", "03", "04", "05"
                });
                //根据值去删除
                client.RemoveItemFromSet("ids", "01");
                client.RemoveItemFromSet("ids", "02");
                var lst = client.GetAllItemsFromSet("ids");
                foreach (var item in lst)
                {
                    WriteLine(item);
                }

                WriteLine("******************");

                //从原来的集合,移除值到新的一个集合总
                client.AddRangeToSet("one", new List <string>()
                {
                    "a", "b", "c", "d"
                });
                client.MoveBetweenSets("one", "two", "a");
                client.MoveBetweenSets("one", "two", "d");

                WriteLine("********交集**********");

                //交叉并补

                client.AddRangeToSet("a", new List <string>()
                {
                    "1", "3", "5"
                });
                client.AddRangeToSet("b", new List <string>()
                {
                    "2", "4", "5", "6"
                });
                //交集
                var jjlist = client.GetIntersectFromSets("a", "b");
                foreach (var item in jjlist)
                {
                    WriteLine(item);
                }

                WriteLine("********并集**********");
                //并集
                var bjlist = client.GetUnionFromSets("a", "b");
                foreach (var item in bjlist)
                {
                    WriteLine(item);
                }


                WriteLine("********差集**********");
                var cjlist = client.GetDifferencesFromSet("a", "b");
                foreach (var item in cjlist)
                {
                    WriteLine(item);
                }

                WriteLine("***zset***");

                //zset 自动去重,而且多一个权重,或者份数的字段,自动排序

                //当不给分数的时候,默认是最大值
                client.AddItemToSortedSet("zsetid", "a", 90);
                client.AddItemToSortedSet("zsetid", "b", 100);
                client.AddItemToSortedSet("zsetid", "c", 80);

                WriteLine("**************");
                //批量添加
                client.AddRangeToSortedSet("zsetidrange", new List <string>()
                {
                    "a", "b"
                }, 100);


                WriteLine("**************");
                //正序查询
                var zsetlist = client.GetAllItemsFromSortedSet("zsetid");
                foreach (var item in zsetlist)
                {
                    WriteLine(item);
                }

                //倒序查询
                var zsetDesc = client.GetAllItemsFromSortedSetDesc("zsetid");
                foreach (var item in zsetDesc)
                {
                    WriteLine(item);
                }


                WriteLine("**************");

                //根据下标获取
                var dic = client.GetRangeFromSortedSet("zsetid", 0, 1);
                foreach (var item in dic)
                {
                    WriteLine(item);
                }

                WriteLine("**************");
                //返回份数
                var dicScore = client.GetRangeWithScoresFromSortedSet("zsetid", 0, 1);
                foreach (var item in dicScore)
                {
                    WriteLine(item.Key + ":" + item.Value);
                }

                WriteLine("**************");

                //把集合中的交集放入到一个新的集合中
                client.AddItemToSortedSet("x", "a", 1);
                client.AddItemToSortedSet("x", "b", 2);
                client.AddItemToSortedSet("x", "c", 3);
                client.AddItemToSortedSet("x", "d", 4);

                client.AddItemToSortedSet("y", "c", 3);
                client.AddItemToSortedSet("y", "d", 4);

                client.AddItemToSortedSet("z", "c", 3);
                client.AddItemToSortedSet("z", "e", 9);

                var newDic = client.StoreIntersectFromSortedSets("newSet", "x", "y", "z");
                WriteLine(newDic);



                ReadLine();
            };
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 向集合中添加数据
 /// </summary>
 /// <param name="item"></param>
 /// <param name="set"></param>
 public static void GetItemToSet(string item, string set)
 {
     redisCli.AddItemToSet(item, set);
 }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            using IRedisClient client = new RedisClient("127.0.0.1", 6379);
            #region Set集合
            client.FlushDb();
            //Set集合自动去重
            var libai = new User
            {
                ID   = "001",
                Name = "李白",
                Age  = "24"
            };
            client.AddItemToSet("set0", JsonConvert.SerializeObject(libai));
            libai = new User
            {
                ID   = "001",
                Name = "李白",
                Age  = "25"
            };
            client.AddItemToSet("set0", JsonConvert.SerializeObject(libai));
            client.AddItemToSet("set0", JsonConvert.SerializeObject(libai));
            Console.WriteLine(client.GetSetCount("set0"));
            //批量操作添加
            client.AddRangeToSet("set1", new List <string> {
                "0", "1", "2", "3"
            });
            //获取Set中的元素
            var sets = client.GetAllItemsFromSet("set1");
            Console.WriteLine("获取set中的元素......");
            foreach (var item in sets)
            {
                Console.WriteLine(item);
            }
            //从set中随机获取一个值
            Console.WriteLine("随机获取set中的一个值......");
            Console.WriteLine(client.GetRandomItemFromSet("set1"));
            //随机删除集合中的元素,并返回删除的值
            Console.WriteLine("随机删除set中的一个值并返回删除的值......");
            var count = client.GetSetCount("set1");
            for (int i = 0; i < count; i++)
            {
                Console.WriteLine(client.PopItemFromSet("set1"));
            }
            //删除set集合中的某个值
            client.AddRangeToSet("set1", new List <string> {
                "0", "1", "2", "3"
            });
            client.RemoveItemFromSet("set1", "1");
            sets = client.GetAllItemsFromSet("set1");
            Console.WriteLine("剩下的值.....");
            foreach (var item in sets)
            {
                Console.WriteLine(item);
            }
            //从原来的集合移除放到新的集合中去
            client.MoveBetweenSets("set1", "set2", "3");
            #region 交叉并补
            client.AddRangeToSet("a", new List <string> {
                "1", "2", "3", "4"
            });
            client.AddRangeToSet("b", new List <string> {
                "4", "3", "5", "6"
            });
            var jiaoList = client.GetIntersectFromSets("a", "b");
            Console.WriteLine("交集");
            foreach (var item in jiaoList)
            {
                Console.WriteLine(item);
            }
            var bingList = client.GetUnionFromSets("a", "b");
            Console.WriteLine("并集");
            foreach (var item in bingList)
            {
                Console.WriteLine(item);
            }
            #endregion
            #endregion
            #region  ZSet集合
            //zset 自动去重,而且多了一个权重,或者分数的字段,自动排序
            client.FlushDb();
            Console.Clear();
            client.AddItemToSortedSet("zsetid", "a");//不给分数赋值,默认是最大的
            client.AddItemToSortedSet("zsetid", "b", 100);
            client.AddItemToSortedSet("zsetid", "c");
            client.AddItemToSortedSet("zsetid", "b");
            client.AddItemToSortedSet("zsetid", "d", 120);
            //get all items order by asc
            var zsetList = client.GetAllItemsFromSortedSet("zsetid");
            Console.WriteLine("the zsetList(asc)");
            foreach (var item in zsetList)
            {
                Console.WriteLine(item);
            }
            //get all items order by desc
            Console.WriteLine("zsetList(desc)");
            var descZsetList = client.GetAllItemsFromSortedSetDesc("zsetid");
            foreach (var item in descZsetList)
            {
                Console.WriteLine(item);
            }
            //get items by index(Desc)
            var zsets = client.GetRangeFromSortedSetDesc("zsetid", 0, 1);
            foreach (var item in zsets)
            {
                Console.WriteLine(item);
            }
            //get items by index(Asc)
            zsets = client.GetRangeFromSortedSet("zsetid", 0, 1);
            foreach (var item in zsets)
            {
                Console.WriteLine(item);
            }
            //get the items with scores
            var zsets1 = client.GetAllWithScoresFromSortedSet("zsetid");
            foreach (var item in zsets1)
            {
                Console.WriteLine(item);
            }
            client.AddItemToSortedSet("zsetid1", "a", 80);//不给分数赋值,默认是最大的
            client.AddItemToSortedSet("zsetid1", "b", 100);
            client.AddItemToSortedSet("zsetid1", "c", 234);
            client.AddItemToSortedSet("zsetid1", "b", 543);
            client.AddItemToSortedSet("zsetid1", "d", 120);
            client.AddItemToSortedSet("zsetid1", "e", 120);

            client.AddItemToSortedSet("zsetid2", "b", 543);
            client.AddItemToSortedSet("zsetid2", "d", 120);
            client.AddItemToSortedSet("zsetid2", "f", 120);
            //将多个集合中的交集放入一个新的集合中
            var dics = client.StoreIntersectFromSortedSets("newzsetid", "zsetid", "zsetid1", "zsetid2");
            #endregion
        }
Ejemplo n.º 28
0
        //在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set
        //这种方式要引用ServiceStack,ServiceStack.Interfaces,ServiceStack.ServiceInterface三个dll
        public static void MainHelper()
        {
            RedisClient client = new RedisClient("127.0.0.1", 6379);

            client.FlushAll();

            #region string
            client.Add <string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(3000));
            while (true)
            {
                if (client.ContainsKey("StringValueTime"))
                {
                    Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get <string>("StringValueTime"), DateTime.Now);
                    Thread.Sleep(1000);
                }
                else
                {
                    Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
                    break;
                }
            }

            client.Add <string>("StringValue", " String和Memcached操作方法差不多");
            Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get <string>("StringValue"));
            #endregion

            #region 存储Entity
            #region 如果想直接存储Entity,对象成员要有{get; set;}属性才行
            Student stu = new Student()
            {
                id = "1001", name = "李四"
            };
            client.Add <Student>("student", stu);
            Student student = client.Get <Student>("student");
            Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", student.id, student.name);
            #endregion

            #region 如果对象成员没有{get; set;},可以通过把对象转换为数据流存储
            Student stud = new Student()
            {
                id = "1001", name = "李四"
            };
            byte[] buff;
            //先将对象转换为数组
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, stud);
                buff = ms.GetBuffer();
            }
            //把数组存入Redis
            client.Add <byte[]>("Entity", buff);
            //取出数组,解析成对象
            if (client.ContainsKey("Entity"))
            {
                using (MemoryStream ms = new MemoryStream(client.Get("Entity")))
                {
                    IFormatter formatter = new BinaryFormatter();
                    Student    Get_stud  = (Student)formatter.Deserialize(ms);
                    Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
                }
            }
            #endregion
            #endregion

            #region Hash
            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");

            List <string> HaskKey = client.GetHashKeys("HashID");
            foreach (string key in HaskKey)
            {
                Console.WriteLine("HashID--Key:{0}", key);
            }

            List <string> HaskValue = client.GetHashValues("HashID");
            foreach (string value in HaskValue)
            {
                Console.WriteLine("HashID--Value:{0}", value);
            }

            List <string> AllKey = client.GetAllKeys(); //获取所有的key。
            foreach (string Key in AllKey)
            {
                Console.WriteLine("AllKey--Key:{0}", Key);
            }
            #endregion

            #region List

            /*
             * list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
             * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
             * 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
             * Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
             */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            int q = client.GetListCount("QueueListId");
            for (int i = 0; i < q; i++)
            {
                Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId"));   //出队(队列先进先出)
            }

            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            int p = client.GetListCount("StackListId");
            for (int i = 0; i < p; i++)
            {
                Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId"));   //出栈(栈先进后出)
            }
            #endregion

            #region Set无序集合

            /*
             * 它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
             */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet <string> hastsetA = client.GetAllItemsFromSet("Set1001");
            foreach (string item in hastsetA)
            {
                Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet <string> hastsetB = client.GetAllItemsFromSet("Set1002");
            foreach (string item in hastsetB)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            HashSet <string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            HashSet <string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            HashSet <string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (string item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }
            #endregion

            #region  SetSorted 有序集合

            /*
             * sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
             * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
             */
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List <string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            foreach (string item in listSetSorted)
            {
                Console.WriteLine("SetSorted有序集合{0}", item);
            }
            #endregion
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            #region 注册 破解6000次
            var  licenseUtils         = typeof(LicenseUtils);
            var  members              = licenseUtils.FindMembers(MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Static, null, null);
            Type activatedLicenseType = null;
            foreach (var memberInfo in members)
            {
                if (memberInfo.Name.Equals("__activatedLicense", StringComparison.OrdinalIgnoreCase) && memberInfo is FieldInfo fieldInfo)
                {
                    activatedLicenseType = fieldInfo.FieldType;
                }
            }

            if (activatedLicenseType != null)
            {
                var licenseKey = new LicenseKey
                {
                    Expiry = DateTime.Today.AddYears(100),
                    Ref    = "ServiceStack",
                    Name   = "Enterprise",
                    Type   = LicenseType.Enterprise
                };

                var constructor = activatedLicenseType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(LicenseKey) }, null);
                if (constructor != null)
                {
                    var activatedLicense      = constructor.Invoke(new object[] { licenseKey });
                    var activatedLicenseField = licenseUtils.GetField("__activatedLicense", BindingFlags.NonPublic | BindingFlags.Static);
                    if (activatedLicenseField != null)
                    {
                        activatedLicenseField.SetValue(null, activatedLicense);
                    }
                }

                Console.WriteLine(licenseKey.ToJson());
            }
            #endregion

            //创建比较器
            var comparator = TaskComparator.GetInstance(1000);

            //ServiceStack.Redis
            RedisClient redisClient = new RedisClient("192.168.8.204", 6379, "superrd", 0);
            //StackExchange.Redis
            IConnectionMultiplexer proxy = ConnectionMultiplexer.Connect("192.168.8.204:6379,password=superrd,DefaultDatabase=0");
            IDatabase db = proxy.GetDatabase();


            //string千次读写对比
            Console.WriteLine("string千次读写对比");
            comparator.Comparator(() => { redisClient.Set("S1", "AAA"); }, () => { db.StringSet("A2", "AAA"); });
            comparator.Comparator(() => { redisClient.Set("S1", "AAA", new TimeSpan(1, 0, 0)); }, () => { db.StringSet("A2", "AAA", new TimeSpan(1, 0, 0)); });
            comparator.Comparator(() => { redisClient.Get <string>("A1"); }, () => { db.StringGet("A2"); });

            //hash千次读写对比
            Console.WriteLine("hash千次读写对比");
            comparator.Comparator(() => { redisClient.SetEntryInHash("H1", "id", "xxx"); }, () => { db.HashSet("H2", "id", "xxx"); });
            comparator.Comparator(() => { redisClient.GetAllEntriesFromHash("H1"); }, () => { db.HashGet("H2", "id"); });

            //list千次读写对比
            Console.WriteLine("list千次读写对比");
            comparator.Comparator(() => { redisClient.PushItemToList("L1", "1"); }, () => { db.ListLeftPush("L2", "1"); });
            comparator.Comparator(() => { redisClient.PopItemFromList("L1"); }, () => db.ListLeftPop("L1"));

            //set千次读写对比
            Console.WriteLine("set千次读写对比");
            comparator.Comparator(() => { redisClient.AddItemToSet("Set1", "xxx"); }, () => { db.SetAdd("Set2", "xxx"); });
            comparator.Comparator(() => { redisClient.GetSetCount("Set1"); }, () => { db.SetLength("Set2"); });

            //SortedSet千次读写对比
            Console.WriteLine("SortedSet千次读写对比");
            comparator.Comparator(() => { redisClient.AddItemToSortedSet("SS1", "item1", 33); }, () => { db.SortedSetAdd("SS2", "item1", 33); });
            comparator.Comparator(() => { redisClient.GetSortedSetCount("SS1"); }, () => { db.SortedSetLength("SS2"); });

            //Geo千次读写对比
            Console.WriteLine("Geo千次读写对比");
            comparator.Comparator(() => { redisClient.GeoAdd("city", 33.33, 33.33, "shanghai"); }, () => { db.GeoAdd("city", 33.34, 33.34, "beijing"); });
            comparator.Comparator(() => { redisClient.FindGeoResultsInRadius("city", "beijing", 333, "m"); }, () => { db.GeoRadius("city", "beijing", 333, GeoUnit.Meters); });

            Console.ReadKey();
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            //教程
            //https://www.cnblogs.com/shiyh/p/8892309.html

            //封装
            //https://blog.csdn.net/wanlong360599336/article/details/46771477

            //在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set

            //面试题
            //https://www.redis.com.cn/redis-interview-questions.html

            RedisClient client = new RedisClient("127.0.0.1", 6379);

            //强制刷新所有DB(生成环境请慎用,会清掉所有DB中的key)。
            client.FlushAll();

            #region string
            //设置过期时间 -Add
            client.Add <string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(30000));
            while (true)
            {
                if (client.ContainsKey("StringValueTime"))
                {
                    Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get <string>("StringValueTime"), DateTime.Now);
                    Thread.Sleep(10000);
                }
                else
                {
                    Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
                    break;
                }
            }

            client.Add <string>("StringValue", " String和Memcached操作方法差不多");
            Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get <string>("StringValue"));

            Student stud = new Student()
            {
                id = "1001", Name = "李四"
            };
            client.Add <Student>("StringEntity", stud);
            Student Get_stud = client.Get <Student>("StringEntity");
            Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.Name);
            #endregion



            #region  Hash
            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");

            List <string> HaskKey = client.GetHashKeys("HashID");

            foreach (string key in HaskKey)
            {
                Console.WriteLine("HashID--Key:{0}", key);
            }

            List <string> HaskValue = client.GetHashValues("HashID");
            foreach (string value in HaskValue)
            {
                Console.WriteLine("HashID--Value:{0}", value);
            }

            List <string> AllKey = client.GetAllKeys(); //获取所有的key。
            foreach (string Key in AllKey)
            {
                Console.WriteLine("AllKey--Key:{0}", Key);
            }
            #endregion



            #region List

            /*
             * list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
             * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
             * 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
             * Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
             */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            //得到List的总数
            var q = client.GetListCount("QueueListId");
            for (int i = 0; i < q; i++)
            {
                //会让键值对消失
                Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId"));   //出队(队列先进先出)
            }


            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            var p = client.GetListCount("StackListId");
            for (int i = 0; i < p; i++)
            {
                //会让键值对消失
                Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId"));   //出栈(栈先进后出)
            }


            #endregion

            #region Set无序集合

            /*
             * 它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
             */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet <string> hastsetA = client.GetAllItemsFromSet("Set1001");
            foreach (string item in hastsetA)
            {
                Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet <string> hastsetB = client.GetAllItemsFromSet("Set1002");
            foreach (string item in hastsetB)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            HashSet <string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            HashSet <string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            HashSet <string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (string item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }

            #endregion

            #region  SetSorted 有序集合

            /*
             * sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
             * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
             */
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List <string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            foreach (string item in listSetSorted)
            {
                Console.WriteLine("SetSorted有序集合{0}", item);
            }
            #endregion

            Console.ReadKey();
        }