C#客户端Redis服务器的分布式缓存

2019-12-30 11:51:33于丽

ASP.NET输出缓存提供者,并且Redis可以用类似的方式进行配置。

Redis Set(集合)和List(列表)

主要要注意的是,Redis列表实现IList<T>,而Redis集合实现ICollection<T>。下面来说说如何使用它们。

当需要区分相同类型的不同分类对象时,使用列表。例如,我们有“mostSelling(热销手机)”和“oldCollection(回收手机)”两个列表:

 



    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>();        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              });        oldCollection.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");  }