1. 程式人生 > 其它 >.NET Core使用Redis

.NET Core使用Redis

部署測試環境

本地啟動redis控制檯 && 安裝redis服務(用於除錯)
1.下載最新版redis,選擇.zip則是免安裝的版本
下載地址 (這是封裝好的基於windows的redis服務)

2.解壓到指定目錄,並執行cmd命令
3.在該資料夾下執行命令:

redis-server.exe redis.windows.conf      

4.看到如下顯示,則表示啟動成功

5.將redis安裝成服務
在該資料夾下執行命令:redis-server.exe --service-install redis.windows.conf

去服務列表查詢服務,可以看到redis服務預設沒有開啟,開啟redis服務(可以設定為開機自動啟動)

之後會發現遠端訪問失敗,需要進行配置,在此不贅述,參考以下的第三篇文章
Tips:
也可以直接選擇安裝Redis-x64-3.0.504.msi

安裝管理工具(可選項)

Redis Desktop Manager

主要用於查詢db
1.連線redis

2.檢視/操作資料

Another Redis Desktop Manager

也可以使用Another Redis Desktop Manager連結

使用

引用

StackExchange.Redis   

建立連線

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
var database = redis.GetDatabase();

使用String

var nameString = "name";
if (await database.StringSetAsync(nameString, "lulu"))
{
    var nameStringValue = await database.StringGetAsync(nameString);
    Console.WriteLine($"{nameString}的值為{nameStringValue}");

    //設定沒有時間限制的key
    await database.KeyIdleTimeAsync(nameString);
    await CheckIfKeyExist(database, nameString);

    //設定5秒後超時的key
    await database.KeyExpireAsync(nameString, DateTime.Now.AddSeconds(5));
    await CheckIfKeyExist(database, nameString);

    await Task.Delay(5000);
    await CheckIfKeyExist(database, nameString);
}

var name_not_exist = await database.StringGetAsync("name_not_exist");
if (name_not_exist.IsNull || name_not_exist.IsNullOrEmpty)
{
    Console.WriteLine($"{nameof(name_not_exist)}為空");
}

使用HashSet

string usersInfoHash = "usersInfo";
await database.HashSetAsync(usersInfoHash, new HashEntry[]
{
    new HashEntry ("number","1"),
    new HashEntry ("name","lulu"),
    new HashEntry ("sex","woman")
});
if (await database.HashExistsAsync(usersInfoHash, "name"))
{
    var count = database.HashLength(usersInfoHash);
    var nameValue = database.HashGet(usersInfoHash, "name");
    var keys = database.HashKeys(usersInfoHash);
    var values = await database.HashValuesAsync("usersInfo");

    await database.HashSetAsync(usersInfoHash, new HashEntry[] { new HashEntry("number", "2") });
    await database.HashSetAsync(usersInfoHash, new HashEntry[] { new HashEntry("age", "99") });
    count = database.HashLength(usersInfoHash);

    //key為HashIncrementTest的value,從1開始遞增,呼叫一次HashIncrement+1
    var hashIncrementTestKey = "HashIncrementTest";
    for (int i = 0; i < 3; i++)
        await database.HashIncrementAsync(usersInfoHash, hashIncrementTestKey);

    //每次呼叫遞減1
    for (int i = 0; i < 5; i++)
        await database.HashDecrementAsync(usersInfoHash, hashIncrementTestKey);

    if (await database.HashDeleteAsync(usersInfoHash, "name"))
    {
        Console.WriteLine($"刪除{usersInfoHash}中的name Field成功");
    }
    long deleteCount = await database.HashDeleteAsync(usersInfoHash, new RedisValue[] { "name", "number", "sex" });
    Console.WriteLine($"刪除{usersInfoHash}中的name/number/sex Field中的{deleteCount}個");

}

//重新命名
if (await database.KeyExistsAsync(usersInfoHash))
    await database.KeyRenameAsync(usersInfoHash, $"rename_{usersInfoHash}");

使用List

//push插入資料
var listKey = "ListKey1";
if (await database.KeyExistsAsync(listKey))
    await database.KeyDeleteAsync(listKey);

database.ListLeftPush(listKey, "Value1");
database.ListLeftPush(listKey, 2);
database.ListLeftPush(listKey, 3.33);

//指定資料後插入資料
await database.ListInsertAfterAsync(listKey, 2, 4);

//指定資料前插入資料
await database.ListInsertBeforeAsync(listKey, 2, 5);

//可以從佇列兩邊取出資料
//取ID最小的值
var leftPopValue = await database.ListLeftPopAsync(listKey);
//取ID最大的值
var rightPopValue = await database.ListRightPopAsync(listKey);

//可以從佇列兩邊插入資料
//ID最小
await database.ListLeftPushAsync(listKey, 6);
await database.ListLeftPushAsync(listKey, 8);
//ID最大
await database.ListRightPushAsync(listKey, 7.77);
//小數數字不精確
var val_7_77 = await database.ListGetByIndexAsync(listKey, 5);
await database.ListRightPushAsync(listKey, "9.99");


//修改指定位置value
Console.WriteLine($"{ await database.ListGetByIndexAsync(listKey, 1)}");
database.ListSetByIndex(listKey, 1, 999);
Console.WriteLine($"{ await database.ListGetByIndexAsync(listKey, 1)}");

var values = database.ListRange(listKey, 1, 10);
Console.WriteLine($"{JsonConvert.SerializeObject(values)}");

var length = database.ListLengthAsync(listKey);

//根據值移除資料
var deleteCount1 = await database.ListRemoveAsync(listKey, 999);

//根據位置移除資料
await database.ListTrimAsync(listKey, 0, 3);

//List允許加入重複值
database.ListLeftPush(listKey, "Value1");
database.ListLeftPush(listKey, "Value1");
database.ListLeftPush(listKey, "Value1");

使用Set

var setKey = "SetKey1";
var setKey2 = "SetKey2";
if (await database.KeyExistsAsync(setKey))
    await database.KeyDeleteAsync(setKey);
if (await database.KeyExistsAsync(setKey2))
    await database.KeyDeleteAsync(setKey2);

await database.SetAddAsync(setKey, "1.223");
await database.SetAddAsync(setKey, "2");
for (decimal i = 0; i < 10;)
{
    await database.SetAddAsync(setKey, i.ToString());
    i = i + (decimal)0.5;
}
if (await database.SetContainsAsync(setKey, 1))
    Console.WriteLine($"{setKey}包含value:1");
else
    Console.WriteLine($"{setKey}不包含value:1");
if (await database.SetContainsAsync(setKey, "2"))
    Console.WriteLine($"{setKey}包含value:2");
else
    Console.WriteLine($"{setKey}不包含value:2");

var length = await database.SetLengthAsync(setKey);
var values = await database.SetMembersAsync(setKey);
Console.WriteLine($"{JsonConvert.SerializeObject(values)}");

//取出資料,資料被移除
var val = await database.SetPopAsync(setKey);

//隨機取出一個數據,資料不被移除
var randomValue = await database.SetRandomMemberAsync(setKey);
//隨機取出n個數據,資料不被移除
var randomValues = await database.SetRandomMembersAsync(setKey, 5);

//set不允許插入相同資料
if (await database.SetAddAsync(setKey, "999"))
    Console.WriteLine($"{setKey}插入資料999:成功");
else
    Console.WriteLine($"{setKey}插入資料999:失敗");
if (await database.SetAddAsync(setKey, "999"))
    Console.WriteLine($"{setKey}插入資料999:成功");
else
    Console.WriteLine($"{setKey}插入資料999:失敗");

var scan1Result = database.SetScan(setKey, "2", 100, 0, 0);
foreach (var redisValue in scan1Result)
{
    Console.WriteLine($"{redisValue}");
}
await database.SetRemoveAsync(setKey, "999");

if (database.SetMove(setKey, setKey2, "2"))
    Console.WriteLine($"將2從{setKey}遷移到{setKey2}:成功(在{setKey}中2被移除)");
else
    Console.WriteLine($"將2從{setKey}遷移到{setKey2}:失敗");

使用SortSet

var sortSetKey = "SortSetKey1";
if (await database.KeyExistsAsync(sortSetKey))
    await database.KeyDeleteAsync(sortSetKey);

await database.SortedSetAddAsync(sortSetKey, 111, 111);
for (double i = 0; i < 10;)
{
    await database.SortedSetAddAsync(sortSetKey, i.ToString(), i);
    i = i + (double)0.5;
}

var sortSetValues = await database.SortAsync(sortSetKey);
Console.WriteLine($"{JsonConvert.SerializeObject(sortSetValues)}");


if (await database.SortedSetAddAsync(sortSetKey, "999", 999))
    Console.WriteLine($"{sortSetKey}插入資料999(分數999):成功");
else
    Console.WriteLine($"{sortSetKey}插入資料999(分數999):失敗");
//失敗
if (await database.SortedSetAddAsync(sortSetKey, "999", 999))
    Console.WriteLine($"{sortSetKey}插入資料999(分數999):成功");
else
    Console.WriteLine($"{sortSetKey}插入資料999(分數999):失敗");
//成功 可以加入同分數不同值的資料
if (await database.SortedSetAddAsync(sortSetKey, "888", 999))
    Console.WriteLine($"{sortSetKey}插入資料888(分數999):成功");
else
    Console.WriteLine($"{sortSetKey}插入資料888(分數999):失敗");
//失敗
if (await database.SortedSetAddAsync(sortSetKey, "999", 888))
    Console.WriteLine($"{sortSetKey}插入資料999(分數888):成功");
else
    Console.WriteLine($"{sortSetKey}插入資料999(分數888):失敗");

var length = await database.SortedSetLengthAsync(sortSetKey);

//根據排名條件讀取value
var rankValues = await database.SortedSetRangeByRankAsync(sortSetKey, start: 0, stop: 10, order: Order.Descending);
Console.WriteLine($"{JsonConvert.SerializeObject(rankValues)}");

//條件同上,讀取value+scroe
var rankWithScoresValues = await database.SortedSetRangeByRankWithScoresAsync(sortSetKey, start: 0, stop: 10, order: Order.Descending);
Console.WriteLine($"{JsonConvert.SerializeObject(rankWithScoresValues)}");

//降序讀取分數在0-10之間的資料value
var scoreValues = await database.SortedSetRangeByScoreAsync(sortSetKey, start: 0, stop: 10, order: Order.Descending);
Console.WriteLine($"{JsonConvert.SerializeObject(scoreValues)}");

//條件同上,讀取value+scroe
var scoreWithScoresValues = database.SortedSetRangeByScoreWithScoresAsync(sortSetKey, start: 0, stop: 10, order: Order.Descending);
Console.WriteLine($"{JsonConvert.SerializeObject(scoreWithScoresValues)}");

//根據value篩選
var rangeByValues = await database.SortedSetRangeByValueAsync(sortSetKey, 0, 998);
Console.WriteLine($"{JsonConvert.SerializeObject(rangeByValues)}");

//返回排名,預設從低到高,從0開始
var rank1 = await database.SortedSetRankAsync(sortSetKey, "888");
//不存在,返回null
var rank2 = await database.SortedSetRankAsync(sortSetKey, "325435435");


if (await database.SortedSetRemoveAsync(sortSetKey, "888"))
{
    Console.WriteLine($"刪除888:成功");
}
else
{
    Console.WriteLine($"刪除888:失敗");
}

//遞增2
var testMember = "testMember";
for (int i = 0; i < 10; i++)
    await database.SortedSetIncrementAsync(sortSetKey, testMember, 2);

for (int i = 0; i < 10; i++)
    await database.SortedSetDecrementAsync(sortSetKey, testMember, 3.6);

示例程式碼

RedisTestDemo

參考資料

Windows下搭建Redis伺服器
windows下安裝Redis並部署成服務