Ejemplo n.º 1
0
        public void UpdateItem(Item item)
        {
            var conf = new RedisEndpoint()
            {
                Host = "xxxxxxxxxxxxxx.redis.cache.windows.net", Password = "******", Ssl = true, Port = 6380
            };

            using (IRedisClient client = new RedisClient(conf))
            {
                IRedisTypedClient <Item> itemClient = client.As <Item>();
                IRedisList <Item>        itemList   = itemClient.Lists["urn:item:" + item.ProductID];

                var index = itemList.Select((Value, Index) => new { Value, Index })
                            .Single(p => p.Value.Id == item.Id).Index;

                var toUpdateItem = itemList.First(x => x.Id == item.Id);

                //var index = itemList.IndexOf(toUpdateItem);

                toUpdateItem.Name  = item.Name;
                toUpdateItem.Price = item.Price;

                itemList.RemoveAt(index);
                if (itemList.Count - 1 < index)
                {
                    itemList.Add(toUpdateItem);
                }
                else
                {
                    itemList.Insert(index, toUpdateItem);
                }

                client.RemoveItemFromSortedSet("urn:Rank", item.Name);
                client.AddItemToSortedSet("urn:Rank", item.Name, item.Price);

                //Publis top 5 Ranked Items
                IDictionary <string, double> Data = client.GetRangeWithScoresFromSortedSet("urn:Rank", 0, 4);
                List <Item> RankList = new List <Item>();
                int         counter  = 0;
                foreach (var itm in Data)
                {
                    counter++;
                    RankList.Add(new Item()
                    {
                        Name = itm.Key, Price = (int)itm.Value, Id = counter
                    });
                }

                var itemJson = JsonConvert.SerializeObject(RankList);
                client.PublishMessage("Rank", itemJson);
                //---------------------------------------------
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     添加单个实体到链表中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="Item"></param>
        /// <param name="timeout"></param>
        public void AddEntityToList <T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient <T> iredisClient = Redis.As <T>();

            if (timeout >= 0)
            {
                Redis.Expire(listId, timeout);
            }
            IRedisList <T> redisList = iredisClient.Lists[listId];

            redisList.Add(Item);
            iredisClient.Save();
        }
Ejemplo n.º 3
0
        public static void addLocalisation(Localisation localisation)
        {
            string host       = "163.172.144.237";
            string elementKey = "master123";

            using (RedisClient redisClient = new RedisClient(host, 6379, elementKey))
            {
                IRedisTypedClient <Localisation> localisationRedis = redisClient.As <Localisation>();
                IRedisList <Localisation>        listUser          = localisationRedis.Lists[$"Localisation:{localisation.pseudo}"];
                //expire list 5h
                redisClient.Custom("EXPIRE", $"Localisation:{localisation.pseudo}", "18000");
                listUser.Add(localisation);
            }
        }
Ejemplo n.º 4
0
        private static void DemoRedisClient()
        {
            const string customerListKey = "urn:customerList";

            using (IRedisClient redisClient = new RedisClient())
            {
                IRedisList customerList = redisClient.Lists[customerListKey];
                customerList.Clear();
                customerList.Add("Joe");
                customerList.Add("Mary");
                customerList.Add("Bob");
                customerList.Add("Frank");
            }

            using (IRedisClient redisClient = new RedisClient())
            {
                IRedisList customerList = redisClient.Lists[customerListKey];

                foreach (string customerName in customerList)
                {
                    Console.WriteLine($"Customer: {customerName}");
                }
            }
        }
Ejemplo n.º 5
0
        public void TestList()
        {
            var client = cacheClient as RedisClient;
            IRedisTypedClient <UserInfoDto> typeClient = client.As <UserInfoDto>();
            IRedisList <UserInfoDto>        list       = typeClient.Lists["TestList"];

            var listUser = GetUsers();

            list.Clear();
            listUser.ForEach(t => list.Add(t));

            var item = list.First(t => t.StaffId == "StaffId_8");

            Console.WriteLine(item);
            Console.ReadLine();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 添加单个实体到链表中
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <param name="Item"></param>
        /// <param name="timeout">過期時間會覆蓋列表之前的過期時間,為-1時保持先前的過期設置</param>
        public void AddEntityToList <T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient <T> iredisClient = Redis.As <T>();
            IRedisList <T>        redisList    = iredisClient.Lists[listId];

            redisList.Add(Item);
            if (timeout >= 0)
            {
                if (timeout == 0)
                {
                    timeout = secondsTimeOut;
                }
                Redis.ExpireEntryIn(listId, TimeSpan.FromSeconds(timeout));
            }
            iredisClient.Save();
        }
Ejemplo n.º 7
0
        public void Working_with_Generic_types()
        {
            using (var redisClient = new RedisClient(TestConfig.SingleHost))
            {
                //Create a typed Redis client that treats all values as IntAndString:
                var typedRedis = redisClient.GetTypedClient <IntAndString>();

                var pocoValue = new IntAndString {
                    Id = 1, Letter = "A"
                };
                typedRedis.SetEntry("pocoKey", pocoValue);
                IntAndString toPocoValue = typedRedis.GetValue("pocoKey");

                Assert.That(toPocoValue.Id, Is.EqualTo(pocoValue.Id));
                Assert.That(toPocoValue.Letter, Is.EqualTo(pocoValue.Letter));

                var pocoListValues = new List <IntAndString> {
                    new IntAndString {
                        Id = 2, Letter = "B"
                    },
                    new IntAndString {
                        Id = 3, Letter = "C"
                    },
                    new IntAndString {
                        Id = 4, Letter = "D"
                    },
                    new IntAndString {
                        Id = 5, Letter = "E"
                    },
                };

                IRedisList <IntAndString> pocoList = typedRedis.Lists["pocoListKey"];

                //Adding all IntAndString objects into the redis list 'pocoListKey'
                pocoListValues.ForEach(x => pocoList.Add(x));

                List <IntAndString> toPocoListValues = pocoList.ToList();

                for (var i = 0; i < pocoListValues.Count; i++)
                {
                    pocoValue   = pocoListValues[i];
                    toPocoValue = toPocoListValues[i];
                    Assert.That(toPocoValue.Id, Is.EqualTo(pocoValue.Id));
                    Assert.That(toPocoValue.Letter, Is.EqualTo(pocoValue.Letter));
                }
            }
        }
Ejemplo n.º 8
0
        public void Working_with_int_list_values()
        {
            const string intListKey = "intListKey";
            var          intValues  = new List <int> {
                2, 4, 6, 8
            };

            //STORING INTS INTO A LIST USING THE BASIC CLIENT
            using (var redisClient = new RedisClient(TestConfig.SingleHost))
            {
                IList <string> strList = redisClient.Lists[intListKey];

                //storing all int values in the redis list 'intListKey' as strings
                intValues.ForEach(x => strList.Add(x.ToString()));

                //retrieve all values again as strings
                List <string> strListValues = strList.ToList();

                //convert back to list of ints
                List <int> toIntValues = strListValues.ConvertAll(x => int.Parse(x));

                Assert.That(toIntValues, Is.EqualTo(intValues));

                //delete all items in the list
                strList.Clear();
            }

            //STORING INTS INTO A LIST USING THE GENERIC CLIENT
            using (var redisClient = new RedisClient(TestConfig.SingleHost))
            {
                //Create a generic client that treats all values as ints:
                IRedisTypedClient <int> intRedis = redisClient.GetTypedClient <int>();

                IRedisList <int> intList = intRedis.Lists[intListKey];

                //storing all int values in the redis list 'intListKey' as ints
                intValues.ForEach(x => intList.Add(x));

                List <int> toIntListValues = intList.ToList();

                Assert.That(toIntListValues, Is.EqualTo(intValues));
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 添加单个实体到链表中
 /// </summary>
 /// <typeparam name="T">对象类型</typeparam>
 /// <param name="key">键</param>
 /// <param name="Item"></param>
 /// <param name="timeout">过期时间 -1:不过期,0:默认过期时间:一天</param>
 public void AddEntityToList <T>(string key, T Item, int timeout = -1)
 {
     try
     {
         IRedisTypedClient <T> iredisClient = base.redisClient.As <T>();
         IRedisList <T>        redisList    = iredisClient.Lists[key];
         redisList.Add(Item);
         iredisClient.Save();
         if (timeout >= 0)
         {
             if (timeout > 0)
             {
                 this.secondsTimeOut = timeout;
             }
             var dtTimeOut = DateTime.Now.AddSeconds(this.secondsTimeOut);
             base.redisClient.ExpireEntryAt(key, dtTimeOut);
         }
     }
     catch (Exception ex)
     {
         string message = string.Format("添加单个的实体到链表中出错");
         LOG.Error(ex, message);
     }
 }
        /// <summary>
        /// to load menuitems to the Redis Cache
        /// </summary>
        /// <param name="restaurantId"></param>
        /// <returns>IRedisList<RestaurantMenu></returns>
        private async Task <IRedisList <RestaurantMenu> > LoadMenuToRedisCache(string restaurantId)
        {
            IRedisList <RestaurantMenu> menuList = null;
            //Get Restaurant Menus
            Dictionary <string, object> restaurantData = await GetWebResponse(_configuration["tacitApiUrl"] + "restaurants/" + restaurantId);

            if (restaurantData != null)
            {
                JArray restaurantMenus = (JArray)restaurantData[RestaurantMenus];
                Dictionary <string, object> menuData = null;

                if (restaurantMenus != null)
                {
                    RestaurantMenu menuCache = null;

                    //Create Redis cache object
                    menuList = getRedisCacheObject(_configuration["CacheKeyPrefix"] + restaurantId);

                    for (int index = 0; index < restaurantMenus.Count(); index++)
                    {
                        JToken menu = (JToken)restaurantMenus[index];

                        String menuId       = menu[Id].ToString();
                        String menuName     = menu[Name].ToString();
                        String deliveryType = menu[DeliveryTypeCode].ToString();

                        //Get MenuItems from each Menu
                        if (!String.IsNullOrEmpty(menuId))
                        {
                            menuData = await GetWebResponse(_configuration["tacitApiUrl"] + "menus/" + menuId.Trim());

                            JArray menuItemGroups = (JArray)menuData[MenuItemGroups];

                            for (int group = 0; group < menuItemGroups.Count(); group++)
                            {
                                JToken menuItemGroup = (JToken)menuItemGroups[group];
                                JArray menuItems     = (JArray)menuItemGroup[MenuItems];

                                if (menuItems != null)
                                {
                                    for (int item = 0; item < menuItems.Count(); item++)
                                    {
                                        JToken menuItem = (JToken)menuItems[item];

                                        String menuItemId   = menuItem[Id].ToString();
                                        String menuItemName = menuItem[Name].ToString();

                                        //Add menuitems to Redis Cache

                                        menuCache = new RestaurantMenu
                                        {
                                            MenuItemId       = menuItemId,
                                            MenuItemName     = menuItemName,
                                            MenuId           = menuId,
                                            MenuName         = menuName,
                                            DeliveryTypeCode = deliveryType
                                        };

                                        menuList.Add(menuCache);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(menuList);
        }
Ejemplo n.º 11
0
        public ActionResult Index()
        {
            string message = string.Empty;
            string host    = "localhost";

            using (var redisClient = new RedisClient(host))
            {
                //Create a 'strongly-typed' API that makes all Redis Value operations to apply against Phones
                IRedisTypedClient <Phone> redis = redisClient.As <Phone>();

                //Redis lists implement IList<T> while Redis sets implement ICollection<T>
                IRedisList <Phone> mostSelling   = redis.Lists["urn:phones:mostselling"];
                IRedisList <Phone> oldCollection = redis.Lists["urn:phones:oldcollection"];

                Person phonesOwner = new Person
                {
                    Id         = 7,
                    Age        = 90,
                    Name       = "OldOne",
                    Profession = "sportsmen",
                    Surname    = "OldManSurname"
                };

                // adding new items to the list
                mostSelling.Add(new Phone
                {
                    Id           = 5,
                    Manufacturer = "Sony",
                    Model        = "768564564566",
                    Owner        = phonesOwner
                });

                mostSelling.Add(new Phone
                {
                    Id           = 8,
                    Manufacturer = "Motorolla",
                    Model        = "324557546754",
                    Owner        = phonesOwner
                });

                var upgradedPhone = new Phone
                {
                    Id           = 3,
                    Manufacturer = "LG",
                    Model        = "634563456",
                    Owner        = phonesOwner
                };

                mostSelling.Add(upgradedPhone);

                // remove item from the list
                oldCollection.Remove(upgradedPhone);

                // find objects in the cache
                IEnumerable <Phone> LGPhones = mostSelling.Where(ph => ph.Manufacturer == "LG");

                // find specific
                Phone singleElement = mostSelling.FirstOrDefault(ph => ph.Id == 8);

                //reset sequence and delete all lists
                redis.SetSequence(0);
                redisClient.Remove("urn:phones:mostselling");
                redisClient.Remove("urn:phones:oldcollection");
            }
            ViewBag.Message = message;
            return(View());
        }
Ejemplo n.º 12
0
 public void Push(CrawlerQueueEntry crawlerQueueEntry)
 {
     _queue.Add(Entry.FromCrawlerQueueEntry(crawlerQueueEntry));
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            string host       = "localhost";
            int    port       = 6379;
            string elementKey = "testKeyRedis";

            using (RedisClient redisClient = new RedisClient(host, port))
            {
                if (redisClient.Get <string>(elementKey) == null)
                {
                    redisClient.Set(elementKey, "some cached value");
                }

                Console.WriteLine("Item value is: {0}", redisClient.Get <string>(elementKey));

                IRedisTypedClient <Phone> phones = redisClient.As <Phone>();
                Phone phoneFive = phones.GetValue("5");
                if (phoneFive == null)
                {
                    phoneFive = new Redis.Phone
                    {
                        Id           = 5,
                        Manufacturer = "Apple",
                        Model        = "xxxx",
                        Owner        = new Person
                        {
                            Id         = 1,
                            Age        = 90,
                            Name       = "OldOne",
                            Profession = "teacher",
                            Surname    = "SurName"
                        }
                    };
                }
                phones.SetValue(phoneFive.Id.ToString(), phoneFive);
                Console.WriteLine("Phone model is: {0},  Phone Owner Name is: {1}", phoneFive.Manufacturer, phoneFive.Owner.Name);

                IRedisList <Phone> mostSelling   = phones.Lists["urn:phones:mostselling"];
                IRedisList <Phone> oldCollection = phones.Lists["urn:phones:oldCollection"];

                Person phoneOwner = new Person
                {
                    Id         = 7,
                    Age        = 90,
                    Name       = "OldOne",
                    Profession = "teacher",
                    Surname    = "SurName"
                };

                mostSelling.Add(new Phone
                {
                    Id           = 5,
                    Manufacturer = "Apple",
                    Model        = "54321",
                    Owner        = phoneOwner
                });

                oldCollection.Add(new Phone
                {
                    Id           = 8,
                    Manufacturer = "Moto",
                    Model        = "111111",
                    Owner        = phoneOwner
                });

                var upgradedPhone = new Phone
                {
                    Id           = 5,
                    Manufacturer = "LG",
                    Model        = "12345",
                    Owner        = phoneOwner
                };

                mostSelling.Add(upgradedPhone);
                Console.WriteLine("Phones in mostSelling list:");
                foreach (Phone ph in mostSelling)
                {
                    Console.WriteLine(ph.Id);
                }

                Console.WriteLine("Phones in oldCollection list:");
                foreach (Phone ph in oldCollection)
                {
                    Console.WriteLine(ph.Id);
                }
                oldCollection.Remove(upgradedPhone);
                IEnumerable <Phone> LGPhones = mostSelling.Where(ph => ph.Manufacturer == "LG");
                foreach (Phone ph in LGPhones)
                {
                    Console.WriteLine("LG phone Id: {0}, LG phone Model: {1}", ph.Id, ph.Model);
                }

                Phone singleElement = oldCollection.FirstOrDefault(ph => ph.Id == 8);
                Console.WriteLine("singleElement phone Id: {0}, singleElement phone Model: {1}", singleElement.Id, singleElement.Model);

                phones.SetSequence(0);

                redisClient.Remove("urn:phones:mostselling");
                redisClient.Remove("urn:phones:oldCollection");

                Console.WriteLine("urn:phones:mostselling Count: {0}", phones.Lists["urn:phones:mostselling"].Count);
            }

            Console.ReadKey();
        }
 private void AddValueToList(IRedisList list, T value) => list.Add(this.Serialize(value));