練習 - 使用 .NET Core 將應用程式連線至 Azure Cache for Redis
在本練習中,您將了解如何:
- 使用 Azure CLI 命令來建立新的 Redis 快取執行個體。
- 使用 StackExchange.Redis 套件,建立 .NET Core 主控台應用程式以從快取新增和擷取值。
必要條件
- 具有有效訂用帳戶的 Azure 帳戶。 如果尚未有訂用帳戶,則可在 https://azure.com/free 註冊免費試用版。
- 其中一個支援平台上的 Visual Studio Code。
- 適用於 Visual Studio Code 的 C# 延伸模組。
- .NET 8 是此練習的目標 Framework。
建立 Azure 資源
登入入口網站:https://portal.azure.com,並開啟 Cloud Shell,然後選取 [Bash] 作為殼層。
建立 Azure 資源的資源群組。 將
<myLocation>
取代為您附近的區域。az group create --name az204-redis-rg --location <myLocation>
使用
az redis create
命令,建立 Azure Cache for Redis 執行個體。 執行個體名稱必須是唯一的,且下列指令碼會嘗試為您產生一個名稱,並將<myLocation>
取代為上一個步驟中使用的區域。 此命令需要幾分鐘的時間來完成。redisName=az204redis$RANDOM az redis create --location <myLocation> \ --resource-group az204-redis-rg \ --name $redisName \ --sku Basic --vm-size c0
在 Azure 入口網站中,瀏覽至所建立的新 Redis 快取。
在 [瀏覽] 窗格的 [設定]/[驗證] 區段中,選取 [存取金鑰],然後將入口網站保持開啟。 複製主要連接字串 (StackExchange.Redis) 值,以後續在應用程式中使用。
建立主控台應用程式
在 Visual Studio Code 終端中執行下列命令,建立主控台應用程式。
dotnet new console -o Rediscache
選取 [檔案] > [開啟資料夾] 並選擇應用程式的資料夾,以在 Visual Studio Code 中開啟應用程式。
將
StackExchange.Redis
套件新增至專案。dotnet add package StackExchange.Redis
刪除 Program.cs 檔案中的任何現有程式碼,並在頂端新增下列
using
陳述式。using StackExchange.Redis;
將下列變數新增至
using
陳述式之後,從入口網站將<REDIS_CONNECTION_STRING>
取代為主要連接字串 (StackExchange.Redis)。// connection string to your Redis Cache string connectionString = "REDIS_CONNECTION_STRING";
在 Program.cs 檔案中附加下列程式碼:
using (var cache = ConnectionMultiplexer.Connect(connectionString)) { IDatabase db = cache.GetDatabase(); // Snippet below executes a PING to test the server connection var result = await db.ExecuteAsync("ping"); Console.WriteLine($"PING = {result.Resp2Type} : {result}"); // Call StringSetAsync on the IDatabase object to set the key "test:key" to the value "100" bool setValue = await db.StringSetAsync("test:key", "100"); Console.WriteLine($"SET: {setValue}"); // StringGetAsync retrieves the value for the "test" key string getValue = await db.StringGetAsync("test:key"); Console.WriteLine($"GET: {getValue}"); }
在 Visual Studio Code 終端中,執行下列命令來建置和執行應用程式。
dotnet build dotnet run
輸出內容應會類似於下列範例:
PING = SimpleString : PONG SET: True GET: 100
返回至入口網站並選取 [Azure Cache for Redis] 刀鋒視窗中的 [活動記錄]。 您可以檢視記錄中的作業。
清除資源
當不再需要資源時,您可以使用 az group delete
命令來移除資源群組。
az group delete -n az204-redis-rg --no-wait