Redis存在五種基礎類型:字符串(String)、隊列(List)、哈希(Hash)、集合(Set)、有序集合(Sorted Set)。本次列舉出Hash的經常使用操做。java
Redis官網:https://redis.io/ git
哈希(Hash)是Redis 中基本的類型,一個 key 對應着一個集合,其中集合中以field-value形式組成一個字典。能夠理解爲一個字典中,單項值部分又是一個字典。每一個哈希(Hash)能夠存儲2^32-1個鍵值對。數據序列化成json格式爲{key:{field1:value1,field2:value2......fieldN:valueN}}。redis
eg:sql
eg:json
eg:緩存
eg:網站
eg:spa
eg:3d
eg:code
eg:
eg:
eg:
eg:
eg:
eg:
eg:數量有限,返回遊標仍然是0。
模擬文章概要信息的Hash存儲並快速獲取,場景以下,網站首頁分頁展現文章概要信息,定義爲熱區文章,如某文章更改內容,則先斷定是否該文章id屬於熱區,如屬於則更改Hash中field對應的值。
一、模擬文章數據,設置一堆種子
var blogOutlineInfoList = new List<BlogOutlineInfo>() { new BlogOutlineInfo() { Id = "9527", Title = "CSharp", Author = "微笑刺客", CreateTime = DateTime.Now, Content = "CSharp從入門到昇仙", CommentCount =0, ReadCount = 0, RecommendCount = 0 }, new BlogOutlineInfo() { Id = "9528", Title = "Mysql", Author = "微笑刺客", CreateTime = DateTime.Now, Content = "Mysql從入門到遁地", CommentCount =0, ReadCount = 0, RecommendCount = 0 }, new BlogOutlineInfo() { Id = "9529", Title = "Docker", Author = "微笑刺客", CreateTime = DateTime.Now, Content = "Docker從入門到轉行", CommentCount =0, ReadCount = 0, RecommendCount = 0 }, ... };
二、將種子數據加入到Redis中(緩存預熱)
foreach (var blogOutlineInfo in blogOutlineInfoList) { //設置Redis_key var blogOutlineInfoKey = $"blogOutlineInfo_{blogOutlineInfo.Id}"; //初始化屬性值 service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.Title), blogOutlineInfo.Title); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.Content), blogOutlineInfo.Content); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.Author), blogOutlineInfo.Author); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.CreateTime), blogOutlineInfo.CreateTime); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.CommentCount), blogOutlineInfo.CommentCount); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.ReadCount), blogOutlineInfo.ReadCount); service.HashSet(blogOutlineInfoKey, nameof(BlogOutlineInfo.RecommendCount), blogOutlineInfo.RecommendCount); }
三、網站中對於某頁須要的數據,根據當前頁面,先從Redis的List中獲取相關文章Id,而後再從Hash中獲取文章概要信息。
四、模擬某文章增長推薦、評論或是訪問量。
#region 增長推薦數量 service.HashIncrement("blogOutlineInfo_9527", "RecommendCount", 1); #endregion #region 更改簡介內容 service.HashSet("blogOutlineInfo_9530", "Content", "k8s從入門到失業"); #endregion #region 增長閱讀量 service.HashIncrement("blogOutlineInfo_9528", "ReadCount", 1); #endregion
五、運行效果,對於第一篇的推薦數量和第二篇的閱讀數量可直接進行更改。
倉庫地址:https://gitee.com/530521314/Partner.TreasureChest.git(RedisOperate文件夾)
2020-05-13,望技術有成後能回來看見本身的腳步