public static void Test() { using (var _redis = new RedisClient(Config.REDIS_DATABASE_ADDRESS)) { _redis.AddItemToSortedSet(Config.RANKING_SET_NAME, "one", 1); _redis.AddItemToSortedSet(Config.RANKING_SET_NAME, "two", 2); _redis.AddItemToSortedSet(Config.RANKING_SET_NAME, "three", 3); _redis.AddItemToSortedSet(Config.RANKING_SET_NAME, "four", 4); _redis.AddItemToSortedSet(Config.RANKING_SET_NAME, "five", 5); var result = _redis.GetRangeFromSortedSetDesc(Config.RANKING_SET_NAME, 1, 3); result.ForEach(each => Console.WriteLine(each)); // 기존 값 수정 _redis.IncrementItemInSortedSet(Config.RANKING_SET_NAME, "two", 9); var fixedResult = _redis.GetRangeFromSortedSetDesc(Config.RANKING_SET_NAME, 1, 3); fixedResult.ForEach(each => Console.WriteLine(each)); // 현재 rank var currentRank = _redis.GetItemIndexInSortedSet(Config.RANKING_SET_NAME, "two"); Console.WriteLine("current rank : " + currentRank); // 전체 수 구하기 Console.WriteLine("total count : " + _redis.GetSortedSetCount(Config.RANKING_SET_NAME)); } }
private static void CargandoLasPoblaciones() { using (var context = new Model.PoblacionesEntities()) { var poblaciones = context.Poblacions.OrderBy(p => p.Name).ToList(); using (IRedisClient client = new RedisClient()) { client.Remove("KEY"); foreach (var poblacion in poblaciones) { var poblacionWithProvince = string.Format("{0} ({1})", poblacion.Name.ToLower(), poblacion.Provincia.Name); var chars = poblacionWithProvince.ToCharArray(); for (var endIndex = 1; endIndex < chars.Length; endIndex++) { var prefix = poblacionWithProvince.Substring(0, endIndex); client.AddItemToSortedSet(Key, prefix, 0); } client.AddItemToSortedSet(Key, poblacionWithProvince + "*", 0); } } } }
//加入有序集合 public static void AddSortSet(RedisClient client) { client.AddItemToSortedSet("SetSorted1001", "1.qhh"); client.AddItemToSortedSet("SetSorted1001", "2.qihaohao"); client.AddItemToSortedSet("SetSorted1001", "3.qihh"); var sortset = client.GetAllItemsFromSortedSet("SetSorted1001"); foreach (var item in sortset) { Console.WriteLine(item); } var sortset1 = client.GetRangeFromSortedSet("SetSorted1001", 0, 0); foreach (var item in sortset1) { Console.WriteLine(item); } var list = client.GetRangeFromSortedSetDesc("SetSorted1001", 0, 0); foreach (var item in list) { Console.WriteLine(item); } }
private void button27_Click(object sender, EventArgs e) { client.AddItemToSortedSet("sortset:name", "ssn1", 1); client.AddItemToSortedSet("sortset:name", "ssn2", 3); client.AddItemToSortedSet("sortset:name", "ssn3", 2); client.AddRangeToSet("sortset:name", new List<string> { "ssn4","ssn5"}); }
private static void TestSortSet() { using (var client = new RedisClient("127.0.0.1", 6379)) { #region "有序Set操作" client.AddItemToSortedSet("HQF.Tutorial.Redis:SA", "B", 2); client.AddItemToSortedSet("HQF.Tutorial.Redis:SA", "C", 1); client.AddItemToSortedSet("HQF.Tutorial.Redis:SA", "D", 5); client.AddItemToSortedSet("HQF.Tutorial.Redis:SA", "E", 3); client.AddItemToSortedSet("HQF.Tutorial.Redis:SA", "F", 4); //有序集合降序排列 Console.WriteLine("\n有序集合降序排列"); client.GetAllItemsFromSortedSetDesc("HQF.Tutorial.Redis:SA").ForEach(e => Console.Write(e + ",")); Console.WriteLine("\n有序集合升序序排列"); client.GetAllItemsFromSortedSet("HQF.Tutorial.Redis:SA").ForEach(e => Console.Write(e + ",")); client.AddItemToSortedSet("HQF.Tutorial.Redis:SB", "C", 2); client.AddItemToSortedSet("HQF.Tutorial.Redis:SB", "F", 1); client.AddItemToSortedSet("HQF.Tutorial.Redis:SB", "D", 3); Console.WriteLine("\n获得某个值在有序集合中的排名,按分数的升序排列"); Console.WriteLine(client.GetItemIndexInSortedSet("HQF.Tutorial.Redis:SB", "D")); Console.WriteLine("\n获得有序集合中某个值得分数"); Console.WriteLine(client.GetItemScoreInSortedSet("HQF.Tutorial.Redis:SB", "D")); Console.WriteLine("\n获得有序集合中,某个排名范围的所有值"); client.GetRangeFromSortedSet("HQF.Tutorial.Redis:SA", 0, 3).ForEach(e => Console.Write(e + ",")); #endregion } }
public IHttpActionResult EchoAtTime([FromBody] EchoMessage model) { if (model == null) { return(BadRequest("Not valid input, Empty Body")); } if (String.IsNullOrWhiteSpace(model.Message)) { return(BadRequest("Not valid input, Empty message")); } if (model.TimeStamp <= DateTimeOffset.MinValue.DateTime) { return(BadRequest($"Not valid input, Time should be greater than {DateTimeOffset.MinValue}")); } if (DateTimeOffset.MaxValue.DateTime <= model.TimeStamp) { return(BadRequest($"Not valid input, Time should be less than {DateTimeOffset.MaxValue}")); } _logger.Info($"Recieve message using EchoAtTime API. Message={model.Message}, Time={model.TimeStamp}"); DateTimeOffset offset = model.TimeStamp; long epocTime = offset.ToUnixTimeSeconds(); _logger.Trace($"Convert message {model}. Set {model.TimeStamp} time to Epc time {epocTime}"); using (var redisClient = new RedisClient(Constants.RedisHost, Constants.RedisPort)) { var message = RedisMessageParser.ToRedisMessage(epocTime, model.Message); redisClient.AddItemToSortedSet(Constants.REDIS_SORTED_SET_NAME, message, epocTime); _logger.Trace($"add message {message} to redis {Constants.REDIS_SORTED_SET_NAME} sorted set"); } return(Ok()); }
public ActionResult Save(string userName, int goal, long?userId) { using (IRedisClient client = new RedisClient()) { var userClient = client.As <User>(); User user; if (userId != null) { user = userClient.GetById(userId); client.RemoveItemFromSortedSet("urn:leaderboard", user.Name); } else { user = new User { Id = userClient.GetNextSequence() }; } user.Name = userName; user.Goal = goal; userId = user.Id; userClient.Store(user); client.AddItemToSortedSet("urn:leaderboard", user.Name, user.Total); } return(RedirectToAction("Index", "Tracker", new { userId = userId })); }
public static bool AddItemToSortedSet(string setId, string value, long score) { using (RedisClient client = GetClient()) { return(client.AddItemToSortedSet(setId, value, score)); } }
// // GET: /Tracker/ public ActionResult Index(long userId, int amount = 0) { using (IRedisClient client = new RedisClient()) { var userClient = client.GetTypedClient <User>(); var user = userClient.GetById(userId); var historyClient = client.GetTypedClient <int>(); var historyList = historyClient.Lists["urn:history:" + userId]; if (amount > 0) { user.Total += amount; userClient.Store(user); historyList.Prepend(amount); historyList.Trim(0, 4); client.AddItemToSortedSet("urn:leaderboard", user.Name, user.Total); } ViewBag.HistoryItems = historyList.GetAll(); ViewBag.UserName = user.Name; ViewBag.Total = user.Total; ViewBag.Goal = user.Goal; ViewBag.UserId = user.Id; } return(View()); }
// GET: Tracker public ActionResult Index(long userId, int amount = 0) { using (IRedisClient client = new RedisClient(new RedisEndpoint { Host = "117.20.40.28", Port = 6379, Password = "******" })) { var userClient = client.As <User>(); var user = userClient.GetById(userId); var historyClient = client.As <int>(); var historyList = historyClient.Lists["urn:history:" + userId]; if (amount > 0) { user.Total += amount; userClient.Store(user); historyList.Prepend(amount); historyList.Trim(0, 4); client.AddItemToSortedSet("urn:leaderboard", user.Name, user.Total); } ViewBag.HistoryItems = historyList.GetAll(); ViewBag.UserName = user.Name; ViewBag.Total = user.Total; ViewBag.Goal = user.Goal; ViewBag.UserId = user.Id; } return(View()); }
public void AddScore(string key, int score) { using (IRedisClient client = new RedisClient()) { client.AddItemToSortedSet(_listName, key, score); } }
public override void AddAllRecords() { for (var i = 0; i < Records.Length; i++) { RedisClient.AddItemToSortedSet(Identifier, Records[i].ToString(), i); } }
public static bool RegisterPlayerRank(string playerId) { using (var _redis = new RedisClient(Config.REDIS_DATABASE_ADDRESS)) { return(_redis.AddItemToSortedSet(Config.RANKING_SET_NAME, playerId, 0)); } }
public void SaveItem(Item item) { var conf = new RedisEndpoint() { Host = "xxxxxxxxxxxxxx.redis.cache.windows.net", Password = "******", Ssl = true, Port = 6380 }; using (IRedisClient client = new RedisClient(conf)) { var itemClient = client.As <Item>(); var itemList = itemClient.Lists["urn:item:" + item.ProductID]; item.Id = itemClient.GetNextSequence(); itemList.Add(item); 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); //--------------------------------------------- } }
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); //--------------------------------------------- } }
public static bool SortedSetAdd(String key, String member, double score) { bool flag = false; using (RedisClient redisClient = new RedisClient(host, port)) { flag = redisClient.AddItemToSortedSet(key, member, score); redisClient.Dispose(); } return(flag); }
public void MatchStart(CharacterClass player1Class, CharacterClass player2Class) { redis.Set("player1HP", player1Class.MaxHealth); redis.Set("player2HP", player2Class.MaxHealth); redis.Set("player1Resource", player1Class.MaxResource); redis.Set("player2Resource", player2Class.MaxResource); redis.Set("action", 1); //redis.Set("player1Class", player1Class); //redis.Set("player2Class", player2Class); redis.AddItemToSortedSet("damageTracker", player1Class.Character.Name, 0); redis.AddItemToSortedSet("damageTracker", player2Class.Character.Name, 0); redis.RemoveAllFromList("combatLog"); redis.PushItemToList("combatLog", "Round started. Fight!"); // redis.Set<bool>("matchInProgress", true); }
// When unreaded messages are read then we set score to 0 for that user public void RemoveUnreadMessages(string user, string fromUser) { // ZADD options but only for Redis 3.0.2 // XX: Only update elements that already exist. Never add elements. // NX: Don't update already existing elements. Always add new elements. // Because in this redis client isn't available ZADD options then if key exists in list we remove it and then add it with score 0 because there is no update in redis sorted set if (redis.RemoveItemFromSortedSet("user:"******":unreadmessages", fromUser)) { redis.AddItemToSortedSet("user:"******":unreadmessages", fromUser, 0); } }
/// <summary> /// 向有序集合中添加元素 /// </summary> /// <param name="set"></param> /// <param name="value"></param> /// <param name="score"></param> public bool AddItemToSortedSet(string set, string value, long score) { try { if (_Client == null) { if (!Init_Server()) { return(false); } } return(_Client.AddItemToSortedSet(set, value, score)); } catch { return(false); } }
public bool AddItemToScoreboard(string item, double score = 0) { try { var itemExists = redis.SortedSetContainsItem(scoreboardId, item); if (!itemExists) { return(redis.AddItemToSortedSet(scoreboardId, item, score)); } _ = redis.IncrementItemInSortedSet(scoreboardId, item, score); return(true); } catch (Exception ex) { var log = ex.ToString(); return(false); } }
public void Success_callback_fails_for_pipeline_using_GetItemScoreInSortedSet() { var redis = new RedisClient(TestConfig.SingleHost); double score = 0; redis.AddItemToSortedSet("testset", "value", 1); using (var pipeline = redis.CreatePipeline()) { pipeline.QueueCommand(u => u.GetItemScoreInSortedSet("testset", "value"), x => { //score should be assigned to 1 here score = x; }); pipeline.Flush(); } Assert.That(score, Is.EqualTo(1)); }
/* * sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定, * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字. */ private static void AddSetSorted(RedisClient client) { if (client == null) { throw new ArgumentNullException("client"); } client.AddItemToSortedSet("SetSorted1001", "A"); client.AddItemToSortedSet("SetSorted1001", "B"); client.AddItemToSortedSet("SetSorted1001", "C"); var listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001"); foreach (var item in listSetSorted) { Console.WriteLine("SetSorted有序集合{0}", item); } client.AddItemToSortedSet("SetSorted1002", "A", 400); client.AddItemToSortedSet("SetSorted1002", "D", 200); client.AddItemToSortedSet("SetSorted1002", "B", 300); // 升序获取第一个值:"D" var list = client.GetRangeFromSortedSet("SetSorted1002", 0, 0); foreach (var item in list) { Console.WriteLine(item); } //降序获取第一个值:"A" list = client.GetRangeFromSortedSetDesc("SetSorted1002", 0, 0); foreach (var item in list) { Console.WriteLine(item); } }
/// <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(); }; }
//在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 }
private void CreateGameQueueEntry() { redis.AddItemToSortedSet(sortedRanksKey, player.ID.ToString(), player.GetRank()); redis.SetEntryInHash(playerInfoKey, playerRankScopeKey, currentRankScope.ToString()); redis.SetEntryInHash(playerInfoKey, gameFoundIDKey, GameNotFoundID.ToString()); }
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 }
/// <summary> /// 向有序集合中添加元素 /// </summary> /// <param name="set"></param> /// <param name="value"></param> /// <param name="score"></param> public static void AddItemToSortedSet(string set, string value, long score) { redisClient.AddItemToSortedSet(set, value, score); }
public static void Show() { using (RedisClient client = new RedisClient("127.0.0.1", 6379)) { //删除当前数据库中的所有Key 默认删除的是db0 client.FlushDb(); //删除所有数据库中的key client.FlushAll(); #region Set 不重复集合 string key = "clay_set"; //投票 #region 添加键值 //就是自动去重,再带去重的功能 var litaibai = new UserInfo() { Id = 1, Name = "李太白" }; //client.AddItemToList(key, JsonConvert.SerializeObject(litaibai)); //client.AddItemToList(key, JsonConvert.SerializeObject(litaibai)); //client.AddItemToSet(key, JsonConvert.SerializeObject(litaibai)); //client.AddItemToSet(key, JsonConvert.SerializeObject(litaibai)); //client.AddItemToSet(key, JsonConvert.SerializeObject(litaibai)); //client.AddItemToSet(key, JsonConvert.SerializeObject(litaibai)); //Console.WriteLine("***完成了"); #endregion #region 随机获取key集合中的一个值,获取当前setid中的所有值 //批量的去操作set 集合 //Console.WriteLine("set 开始了"); client.AddRangeToSet(key, new List <string>() { "001", "001", "002", "003", "003", "004" }); //////当前setid中的值数量 //Console.WriteLine(client.GetSetCount(key)); ////随机获取key集合中的一个值 如果有需要取随机数也可以用 //Console.WriteLine(client.GetRandomItemFromSet(key)); ////获取当前setid中的所有值 //var lists = client.GetAllItemsFromSet(key); //Console.WriteLine("展示所有的值"); //foreach (var item in lists) //{ // Console.WriteLine(item); //} #endregion #region 随机删除key集合中的一个值 //client.AddRangeToSet(key, new List<string>() { "001", "001", "002" }); //////随机删除key集合中的一个值 返回当前删掉的这个值 //Console.WriteLine("随机删除的值" + client.PopItemFromSet(key)); //var lists = client.GetAllItemsFromSet(key); //Console.WriteLine("展示删除之后所有的值"); //foreach (var item in lists) //{ // Console.WriteLine(item); //} #endregion #region 根据小key 删除 一个key 对象多个value //client.AddRangeToSet(key, new List<string>() { "001", "001", "002" }); //client.RemoveItemFromSet(key, "001"); //var lists = client.GetAllItemsFromSet(key); //Console.WriteLine("展示删除之后所有的值"); //foreach (var item in lists) //{ // Console.WriteLine(item); //} #endregion #region 从fromkey集合中移除值为value的值,并把value添加到tokey集合中 //client.AddRangeToSet("fromkey", new List<string>() { "003", "001", "002", "004" }); //client.AddRangeToSet("tokey", new List<string>() { "001", "002" }); ////从fromkey 中把元素004 剪切到tokey 集合中去 //client.MoveBetweenSets("fromkey", "tokey", "004"); //Console.WriteLine("fromkey data ~~~~~~"); //foreach (var item in client.GetAllItemsFromSet("tokey")) //{ // Console.WriteLine(item); //} //Console.WriteLine("tokey data ~~~~~~"); //foreach (var item in client.GetAllItemsFromSet("tokey")) //{ // Console.WriteLine(item); //} #endregion #region 并集 把两个集合合并起来,然后去重 //client.AddRangeToSet("keyone", new List<string>() { "001", "002", "003", "004" }); //client.AddRangeToSet("keytwo", new List<string>() { "001", "002", "005" }); //var unionlist = client.GetUnionFromSets("keyone", "keytwo"); //Console.WriteLine("返回并集结果"); //foreach (var item in unionlist) //{ // Console.WriteLine(item); //} //把 keyone 和keytwo 并集结果存放到newkey 集合中 //client.StoreUnionFromSets("newkey", "keyone", "keytwo"); //Console.WriteLine("返回并集结果的新集合数据"); //foreach (var item in client.GetAllItemsFromSet("newkey")) //{ // Console.WriteLine(item); //} #endregion #region 交集 获取两个集合中共同存在的元素 //client.AddRangeToSet("keyone", new List<string>() { "001", "002", "003", "004" }); //client.AddRangeToSet("keytwo", new List<string>() { "001", "002", "005" }); //var Intersectlist = client.GetIntersectFromSets("keyone", "keytwo"); //Console.WriteLine("交集的结果"); //foreach (var item in Intersectlist) //{ // Console.WriteLine(item); //} ////把 keyone 和keytwo 交集结果存放到newkey 集合中 //client.StoreIntersectFromSets("newkey", "keyone", "keytwo"); //Console.WriteLine("返回交集结果的新集合数据"); //foreach (var item in client.GetAllItemsFromSet("newkey")) //{ // Console.WriteLine(item); //} #endregion #endregion #region sorted set //string zsett_key = "clay_zset"; ////添加一个kye 如果有相同的值得花,则会替换(覆盖)进去,不会因为分数保留 //client.AddItemToSortedSet(zsett_key, "cc", 33); //client.AddItemToSortedSet(zsett_key, "cc", 44); //client.AddItemToSortedSet(zsett_key, "cc", 22); //Console.WriteLine("ok"); ////获取当前value的结果 //Console.WriteLine(client.GetItemIndexInSortedSet(zsett_key, "cc")); ////批量操作多个key ,给多个key 赋值1 //client.AddRangeToSortedSet(zsett_key, new List<string>() { "a", "b" }, 1); //foreach (var item in client.GetAllItemsFromSortedSet(zsett_key)) //{ // Console.WriteLine(item); //} client.AddItemToSortedSet("蜀国", "刘备", 5); client.AddItemToSortedSet("蜀国", "关羽", 2); client.AddItemToSortedSet("蜀国", "张飞", 3); client.AddItemToSortedSet("魏国", "刘备", 5); client.AddItemToSortedSet("魏国", "关羽", 2); client.AddItemToSortedSet("蜀国", "张飞", 3); ////获取 key为蜀国的下标0,到2 IDictionary <String, double> Dic = client.GetRangeWithScoresFromSortedSet("蜀国", 0, 2); foreach (var r in Dic) { Console.WriteLine(r.Key + ":" + r.Value); } //var DicString = client.StoreIntersectFromSortedSets("2", "蜀国", "魏国"); //var ss = client.GetAllItemsFromSortedSet("2"); //foreach (var r in DicString) //{ // Console.WriteLine(r.Key + ":" + r.Value); //} //int int32 #endregion } }
public bool AddItemToSortedSet(string setId, string value) { return(redisClient.AddItemToSortedSet(setId, value)); }
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(); }