如何在ASP.NET Core中使用Redis

注:本文提到的代碼示例下載地址> https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418html

Redis 是一個開源的內存中的數據結構存儲系統,能夠用做數據庫、緩存和消息中間件。它支持多種類型的數據結構:字符串,哈希表,列表,集合,有序集等等。git

Redis 官方沒有推出Windows版本,卻是由Microsoft Open Tech提供了Windows 64bit 版本支持。github

如何在Windows機器上安裝Redis=>下載安裝文件Redis-x64-3.2.100.msi,安裝完畢以後,打開service管理器,找到Redis服務,並將其啓動。redis

 

前期準備:數據庫

1.推薦使用Visual Studio 2015 Update3做爲你的IDE,下載地址:www.visualstudio.com緩存

2.你須要安裝.NET Core的運行環境以及開發工具,這裏提供VS版:www.microsoft.com/net/core數據結構

建立項目:函數

打開VS 2015,新建->項目->C#模板->Web->ASP.NET Core Web Application(.NET Core)工具

 

 選擇好路徑,項目名爲CSCoreRedis,肯定後選擇Web Application,身份驗證選擇無。post

項目建立完以後,在CSCoreRedis項目上右鍵選擇管理NuGet包,搜索StackExchange.Redis並安裝。

咱們將用這個庫提供的接口去操做Redis。

代碼:

首先要在HomeController.cs中添加Redis的鏈接,若是你不是用的本地Redis服務,請自行修改鏈接字符串。   

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
    return ConnectionMultiplexer.Connect("localhost,abortConnect=false"); }); public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } }

添加構造函數,初始化database和List。這裏使用ListLeftPush是爲了在後面用ListRange的時候從左到右取能取到最新的數據。

public static string ListKeyName = "MessageList";
public HomeController() { db = Connection.GetDatabase(); if (db.IsConnected(ListKeyName) && (!db.KeyExists(ListKeyName) || !db.KeyType(ListKeyName).Equals(RedisType.List))) { //Add sample data.  db.KeyDelete(ListKeyName); //Push data from the left db.ListLeftPush(ListKeyName, "TestMsg1"); db.ListLeftPush(ListKeyName, "TestMsg2"); db.ListLeftPush(ListKeyName, "TestMsg3"); db.ListLeftPush(ListKeyName, "TestMsg4"); } }

修改Index.cshtml文件,添加輸入框及按鈕

<form action="/Home/SendMessage" method="post">
    <input type="text" name="message" style="width:250px" />
    <input name="btnSend" value="Send" type="submit" style="margin-left:5px" />
</form>

在controller中添加SendMessage方法

[HttpPost]
public ActionResult SendMessage(string message) { if (db.IsConnected(ListKeyName)) { db.ListLeftPush(ListKeyName, message); } return RedirectToAction("Index"); }

顯示錯誤信息或信息列表

@if (@ViewData["Error"] != null)
{
    <h2>@ViewData["Error"]</h2> } else { <div id="MessageList"> <h3>Latest messages</h3> @foreach (var msg in Model) { <div>@Html.DisplayFor(modelItem => msg) </div> } </div> }

 咱們來看一下運行結果

在輸入框中輸入字符,按下Send按鈕,頁面上將會顯示最新的5條信息。

 

下載完整的代碼,請訪問 https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418

要了解更多關於Redis的信息,請訪問Redis官方網站http://www.redis.io/

關於StackExchange.Redis的詳細文檔,請訪問https://github.com/StackExchange/StackExchange.Redis

如需瞭解微軟Azure Redis 緩存,請訪問https://azure.microsoft.com/zh-cn/services/cache/

相關文章
相關標籤/搜索