【原創】詳細案例解剖——淺談Redis緩存的常用5種方式(String,Hash,List,set,SetSorted )


很多小伙伴沒接觸過Redis,以至於去學習的時候感覺雲里霧里的,就有一種:教程隨你出,懂了算我輸的感覺。

每次聽圈內人在談論的時候總是插不上話,小編就偷偷去了解了一下,也算是初入門徑。

然后就整理了一下,很簡單的一個demo(小編用的是C#語法進行demo編寫),我們一起來解剖一下。

總共分為兩步:

    1、安裝Redis服務器(其實就是一個CMD黑窗窗)。

    2、編寫代碼(引入動態鏈接庫、編寫5種常用存儲數據類型)

1、安裝Redis服務器(Windows系統)

1)、我們先去微軟官網下載一個Redis GitHub:https://github.com/MSOpenTech/redis/releases,然后選擇你喜歡的版本zip或msi下載。

小編下載了一個放在百度雲:https://pan.baidu.com/s/1M7ztZvOmR0YPehbRujkM6Q,提取碼:uqmw

下載好了后在C盤建立一個redis文件夾,解壓到redis。

相關程序說明:

    redis.windows.conf 是redis的配置文件。

    redis-server.exe 服務器端。

    redis-cli 命令行客戶端。

    redis-benchmark:Redis性能測試工具,測試Redis在你的系統及你的配置下的讀寫性能。

2)、啟動服務

Windows+R輸入cmd 運行,進入我們解壓文件的目錄(按回車):

cd C:\redis\Redis-x64-3.0.504

 

進入redis目錄后,在命令行輸入如下命令后回車:

redis-server  redis.windows.conf

也可以該命令保存為文件 startup.bat,保存在根目錄下,下次就可以直接運行startup.bat啟動,

 

 

 到這里我們服務器就安裝完成了,接下來我們進行測試,看是否能用(是否安裝成功)

3)、測試

另外開啟一個命令行窗口 進入redis目錄下 (注意修改自己的ip(通過ipconfig來查看自己本地的ip地址)),第一個命令窗口不要關。

cd C:\redis\Redis-x64-3.0.504

運行如下命令:后面添加--raw,在輸出中文時可避免出現亂碼,Ip是你自己本地的ip

redis-cli.exe -h 192.168.0.43 -p 6379 --raw

寫入redis緩存,輸入如下代碼回車,注意寫入的值這里不能有空格,也就是或HelloWorld是一個字符串。

set keyStr HelloWorld

讀入redis緩存,輸入如下代碼回車

get keyStr

 

到這里我們redis服務器就安裝好了,接下來我們寫代碼測試(記住,命令窗口(黑窗窗)不能關閉,一旦關閉redis就關閉了)

2、編寫代碼(我們使用C#語法進行編寫)

我先新建一個控制台應用程序:RedisApplication

然后引入三個動態鏈接庫到項目里面,百度網盤下載鏈接如下:https://pan.baidu.com/s/1xySWqoootlF9la0NJQSVYg,提取碼:qlyx

新建一個學生類:Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisApplication
{
    public class Student
    {
        public string id { get; set; }
        public string name { get; set; }
    }
}

在Program.cs編寫redis緩存與讀取,五種方法均在里面,運行時注意吧不測試的注釋掉

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RedisApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            //在Redis中存儲常用的5種數據類型:string,Hash,List,SetSorted ,set
            /// string
            /// Hash
            /// List
            /// SetSorted
            /// set

            RedisClient client = new RedisClient("192.168.0.43", 6379);  //鏈接Redis服務器
            client.FlushAll();  //命令用於清空整個Redis服務器的數據(刪除所有數據庫的所有密鑰)。

            #region string
            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.王麻子");
            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
        }
    }
}

 

如下五種方法:

 

我們運行Hash這個方法讀取緩存的數據:

 

 很顯然,讀取成功。

到這里我們的簡單redis緩存就完成了,是不是很簡單,只有理清楚邏輯,一切都好辦。

然后小編設想一下,如果我們需要緩存文件,如視頻、圖片,我們是不是可以先轉換為二進制流就行存儲讀取呢。

這個問題就交給你辣,加油,你可以的。

 

歡迎關注訂閱我的微信公眾平台【熊澤有話說】,更多好玩易學知識等你來取
作者:熊澤-學習中的苦與樂
公眾號:熊澤有話說
出處:https://www.cnblogs.com/xiongze520/p/10267804.html
創作不易,任何人或團體、機構全部轉載或者部分轉載、摘錄,請在文章明顯位置注明作者和原文鏈接。  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM