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

ASP.NET?Core中使用Redis實現(xiàn)緩存

 更新時間:2022年03月23日 09:40:23   作者:.NET開發(fā)菜鳥  
本文詳細講解了ASP.NET?Core中使用Redis實現(xiàn)緩存的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、前言

我們這里以StackExchange.Redis為例,講解如何在ASP.NET Core中如何使用Redis實現(xiàn)緩存。首先需要安裝Redis和RedisDesktopManager。RedisDesktopManager用來查看Redis緩存里面的數(shù)據(jù)。如何安裝Redis這里不在講述。

二、安裝StackExchange.Redis

在NuGet上安裝StackExchange.Redis,如下圖所示:

 安裝完成以后在依賴項里面就可以看到:

三、添加配置

 在appsettings.json文件里面添加Redis相關(guān)配置信息:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Redis": {
    "Default": {
      "Connection": "127.0.0.1:6379",
      "InstanceName": "local",
      "DefaultDB": 8
    }
  }
}

四、Redis幫助類

 創(chuàng)建Redis幫助類,代碼如下:

using StackExchange.Redis;
using System;
using System.Collections.Concurrent;

namespace RedisDemo
{
    public class RedisHelper : IDisposable
    {
        //連接字符串
        private string _connectionString;
        //實例名稱
        private string _instanceName;
        //默認數(shù)據(jù)庫
        private int _defaultDB; 
        private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
        public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
        {
            _connectionString = connectionString;
            _instanceName = instanceName;
            _defaultDB = defaultDB;
            _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
        }

        /// <summary>
        /// 獲取ConnectionMultiplexer
        /// </summary>
        /// <returns></returns>
        private ConnectionMultiplexer GetConnect()
        {
            return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
        }

        /// <summary>
        /// 獲取數(shù)據(jù)庫
        /// </summary>
        /// <param name="configName"></param>
        /// <param name="db">默認為0:優(yōu)先代碼的db配置,其次config中的配置</param>
        /// <returns></returns>
        public IDatabase GetDatabase()
        {
            return GetConnect().GetDatabase(_defaultDB);
        }

        public IServer GetServer(string configName = null, int endPointsIndex = 0)
        {
            var confOption = ConfigurationOptions.Parse(_connectionString);
            return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
        }

        public ISubscriber GetSubscriber(string configName = null)
        {
            return GetConnect().GetSubscriber();
        }

        public void Dispose()
        {
            if (_connections != null && _connections.Count > 0)
            {
                foreach (var item in _connections.Values)
                {
                    item.Close();
                }
            }
        }
    }
}

五、添加服務(wù)依賴項

 在Startup.cs類的ConfigureServices方法里面添加服務(wù)注入:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace RedisDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //redis緩存
            var section = Configuration.GetSection("Redis:Default");
            //連接字符串
            string _connectionString = section.GetSection("Connection").Value;
            //實例名稱
            string _instanceName = section.GetSection("InstanceName").Value;
            //默認數(shù)據(jù)庫 
            int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");           
            services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

六、在控制器中使用

 新建一個控制器,然后通過構(gòu)造函數(shù)注入:

using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace RedisDemo.Controllers
{
    [Route("api/redis")]
    [ApiController]
    public class RedisController : ControllerBase
    {
        private readonly IDatabase _redis;
        public RedisController(RedisHelper client)
        {
            _redis = client.GetDatabase();
        }

        [HttpGet]
        public string Get()
        {
            // 往Redis里面存入數(shù)據(jù)
            _redis.StringSet("Name", "Tom");
            // 從Redis里面取數(shù)據(jù)
            string name = _redis.StringGet("Name");
            return name;
        }
    }
}

七、測試

運行程序,使用Postman測試控制器:

然后通過RedisDesktopManager查看Redis里面的數(shù)據(jù),這里使用的Db8數(shù)據(jù)庫:

到此這篇關(guān)于ASP.NET Core中使用Redis實現(xiàn)緩存的文章就介紹到這了。希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • .NET Framework常用ORM框架iBatis.Net操作數(shù)據(jù)庫的方法

    .NET Framework常用ORM框架iBatis.Net操作數(shù)據(jù)庫的方法

    iBatis.Net 是一個輕量級的 ORM 框架,它允許開發(fā)者通過直接編寫 SQL 查詢來操作數(shù)據(jù)庫,并將查詢結(jié)果映射到對象模型中,本文將通過實際的代碼示例,詳細介紹如何在 .NET 環(huán)境中使用 iBatis.Net 進行數(shù)據(jù)庫操作,感興趣的朋友一起看看吧
    2024-08-08
  • ASP.NET MVC中異常處理&自定義錯誤頁詳析

    ASP.NET MVC中異常處理&自定義錯誤頁詳析

    當ASP.NET MVC程序出現(xiàn)了異常,怎么處理更加規(guī)范?下面這篇文章主要給大家介紹了關(guān)于ASP.NET MVC中異常處理&自定義錯誤頁的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起學(xué)習學(xué)習吧。
    2018-04-04
  • .net core使用redis基于StackExchange.Redis

    .net core使用redis基于StackExchange.Redis

    這篇文章主要為大家詳細介紹了.net core使用redis基于StackExchange.Redis的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • 利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程詳解

    利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程詳解

    這篇文章主要給大家介紹了關(guān)于利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起看看吧
    2018-08-08
  • ASP.NET MVC視圖尋址

    ASP.NET MVC視圖尋址

    這篇文章介紹了ASP.NET MVC視圖尋址的方法,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧
    2022-03-03
  • asp.net 不用GridView自帶刪除功能,刪除一行數(shù)據(jù)

    asp.net 不用GridView自帶刪除功能,刪除一行數(shù)據(jù)

    數(shù)據(jù)表一定要有個ID的主鍵值,你的gridview要設(shè)定一下DataKeyNames="ID"這個屬性值,接下的事件就好多了,寫個OnRowDeleting事件就可以了。
    2009-11-11
  • Asp.net 連接MySQL的實現(xiàn)代碼[]

    Asp.net 連接MySQL的實現(xiàn)代碼[]

    ASP.NET連接MySQL需要一個組件(.net本身不提供訪問MySQL的驅(qū)動)MySQL.Data.Dll,此為官方提供(純C#開發(fā),開源噢),有多個版本選擇,采用的數(shù)據(jù)訪問模式為ADO.NET,跟asp.net訪問sqlserver很像,非常簡單。
    2009-08-08
  • Asp.net XMLHTTP封裝類(GET,Post發(fā)送和接收數(shù)據(jù))

    Asp.net XMLHTTP封裝類(GET,Post發(fā)送和接收數(shù)據(jù))

    XMLHTTP封裝類可以向遠程發(fā)送URL和參數(shù),接受返回信息(無亂碼)
    2008-11-11
  • ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章(十)

    ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章(十)

    這篇文章主要為大家詳細介紹了ASP.NET MVC5網(wǎng)站開發(fā)修改及刪除文章,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2015-09-09
  • asp.net 簡單工廠模式和工廠方法模式之論述

    asp.net 簡單工廠模式和工廠方法模式之論述

    簡單工廠模式的最大優(yōu)點在于工廠類中包含了必要的邏輯判斷,根據(jù)客戶端的選擇條件動態(tài)實例化相關(guān)的類,對于客戶端來說,去除了于具體產(chǎn)品的依賴
    2011-12-12

最新評論