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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了详解如何在ASP.NET Core中使用Redis脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

redis 是一个开的内存中的数据结构存储系统,可以用作数据库、缓存和消息中间件。它支持多种类型的数据结构:字符串,哈希表,列表,集合,有序集等等

Redis 官方没有推出Windows版本,倒是由Microsoft OPEn Tech提供了Windows 64bIT 版本支持。

何在Windows机器上安装Redis=>下载安装文件Redis-x64-3.2.100.msi,安装完毕之后,打开service管理器,找到Redis服务,并将其启动。

 前期准备:

1.推荐使用Visual Studio 2015 Update3作为你的IDE,下载地址:https://www.js-code.com/softjc/446184.html

2.你需要安装.NET Core的运行环境以及开发工具,这里提供VS版:https://www.js-code.com/softs/472362.html

创建项目:

打开VS 2015,新建->项目->C#模板->Web->ASP.NET Core Web Application(.NET Core)

选择好路径,项目名为CSCoreRedis,确定后选择Web Application,身份验证选择无。

项目创建完之后,在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条信息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的详解如何在ASP.NET Core中使用Redis全部内容,希望文章能够帮你解决详解如何在ASP.NET Core中使用Redis所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。