如何在ASP.NET Core中使用Redis

news/2025/2/26 21:36:47

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

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

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

如何在Windows机器上安装Redis=>下载安装文件Redis-x64-3.2.100.msi,安装完毕之后,打开service管理器,找到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,身份验证选择无。

项目创建完之后,在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/

更多脚本样例, 访问微软One Code样例库:http://aka.ms/onescriptsamples 更多代码样例, 访问微软One Script样例库:http://aka.ms/onecodesamples

http://www.niftyadmin.cn/n/4611444.html

相关文章

node请求页面时自动下载

问题如下&#xff0c;这里浏览器访问接口会直接下载 const router require(express).Router(); const fs require(fs);router.get(/index.html,(req,res)>{fs.readFile(./views/cookie.html,utf8,(err,data)>{if(err) res.send(error);else res.send(data);}); }); mo…

Android中EditText显示明文与密码的两种方式

效果图如下所述&#xff1a; <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android" xmlns:tools"http://schemas.android.com/tools" android:layout_width&qu…

context must be a dict rather解决

原来的代码 def depart_edit(request, nid):# 修改部门# 根据获取到的nid查询数据库row models.Department.objects.filter(idnid).first()# 转发数据row到depart_edit.htmlreturn render(request, depart_edit.html, row)最终发现问题render()第三个参数应该是对象形式 def…

OS层面删除数据文件后的恢复方式(LINUX):

此次删除数据文件后&#xff0c;请不要重启数据库或者关闭数据库&#xff0c;可直接在线恢复。测试方式&#xff1a;先从数据库中查看数据库数据文件的文件号及路径&#xff1a; SQL> select FILE# ,name from v$datafile;FILE# NAME ---------- -----------------------…

pyside2____1.安装和案列

安装 pip install pyside2 -i https://pypi.douban.com/simple/ 代码main.py from PySide2.QtWidgets import QApplication, QMainWindow, QPlainTextEdit, QPushButtonapp QApplication() # 总程序 window QMainWindow() # 主窗口对象 window.resize(500, 400) window.m…

Could not autowire.No beans of ‘userMapper‘ type found.

这里并没有错误&#xff0c;但是IDEA报红 package com.example.demo.mapper;import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.t…

腾讯iphone面试题(转)

1Objective&#xff0d;C内部的实现2CALayer和View的关系3 http协议&#xff0c;tcp/ip4 UITableView的那些元素是可以自定义的&#xff1f;5 c语言的&#xff0c;定义变量&#xff0c;比如int&#xff0c;在什么情况下&#xff0c;其最大值是不同的6 比较32位平台和64位平台不…

spring boot jwt完整过程

首先源码https://gitee.com/mobile191llx/spring-boot-jwt.git 接着项目目录结构 项目开始 1.新建项目名称为demo、选择maven什么都不要勾选 2.依赖pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache…