欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解如何在ASP.NET Core中使用Redis

 更新時間:2016年12月03日 09:01:41   作者:微軟一站式示例代碼庫  
Redis 是一個開源的內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),本篇文章主要介紹了如何在ASP.NET Core中使用Redis,具有一定的參考價值,有興趣的可以了解一下。

Redis 是一個開源的內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),可以用作數(shù)據(jù)庫、緩存和消息中間件。它支持多種類型的數(shù)據(jù)結(jié)構(gòu):字符串,哈希表,列表,集合,有序集等等。

Redis 官方?jīng)]有推出Windows版本,倒是由Microsoft Open Tech提供了Windows 64bit 版本支持。

如何在Windows機(jī)器上安裝Redis=>下載安裝文件Redis-x64-3.2.100.msi,安裝完畢之后,打開service管理器,找到Redis服務(wù),并將其啟動。

 前期準(zhǔn)備:

1.推薦使用Visual Studio 2015 Update3作為你的IDE,下載地址:http://www.dbjr.com.cn/softjc/446184.html

2.你需要安裝.NET Core的運(yùn)行環(huán)境以及開發(fā)工具,這里提供VS版:http://www.dbjr.com.cn/softs/472362.html

創(chuàng)建項(xiàng)目:

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

選擇好路徑,項(xiàng)目名為CSCoreRedis,確定后選擇Web Application,身份驗(yàn)證選擇無。

項(xiàng)目創(chuàng)建完之后,在CSCoreRedis項(xiàng)目上右鍵選擇管理NuGet包,搜索StackExchange.Redis并安裝。

我們將用這個庫提供的接口去操作Redis。

代碼:

首先要在HomeController.cs中添加Redis的連接,如果你不是用的本地Redis服務(wù),請自行修改連接字符串。

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

public static ConnectionMultiplexer Connection
{
  get
  {
    return lazyConnection.Value;
  }
}

添加構(gòu)造函數(shù),初始化database和List。這里使用ListLeftPush是為了在后面用ListRange的時候從左到右取能取到最新的數(shù)據(jù)。

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> 
}

我們來看一下運(yùn)行結(jié)果

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論