分布式缓存能够处理大量的动态数据,因此比较适合应用在Web 2.0时代中的社交网站等需要由用户生成内容的场景。从本地缓存扩展到分布式缓存后,关注重点从CPU、内存、缓存之间的数据传输速度差异也扩展到了业务系统、数据库、分布式缓存之间的数据传输速度差异。
如图:
实现步骤
1.首先配置Redis,这里不做详细记录,自己百度安装
2.打开你的项目,在appsettings.json配置如下代码
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "Session_Timeout": "30", "redis_connstr": { "master_conn": "127.0.0.1:6379,password=root" } }
这里配置了session的时间和Redis的连接字符串
3.使用NuGet工具包,安装Microsoft.Extensions.Caching.Redis,具体操作不详细讲解
4.我们这里封装一个类ConfigHelper,用来读取appsettings.json,具体代码如下:
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace ProjectManage { public class ConfigHelper { private static IConfiguration _configuration; static ConfigHelper() { //在当前目录或者根目录中寻找appsettings.json文件 var fileName = "appsettings.json"; var directory = AppContext.BaseDirectory; directory = directory.Replace("\", "/"); var filePath = $"{directory}/{fileName}"; if (!File.Exists(filePath)) { var length = directory.IndexOf("/bin"); filePath = $"{directory.Substring(0, length)}/{fileName}"; } var builder = new ConfigurationBuilder() .AddJsonFile(filePath, false, true); _configuration = builder.Build(); } public static string GetSectionValue(string key) { return _configuration.GetSection(key).Value; } public static IEnumerable<IConfigurationSection> GetChildrenValue(string key) { return _configuration.GetSection(key).GetChildren(); } } }
5.打开Startup.cs文件,导入命名空间using Microsoft.Extensions.DependencyInjection.Extensions,在ConfigureServices方法中写入以下内容:
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDistributedRedisCache(option => { //redis 数据库连接字符串 option.Configuration = ConfigHelper.GetSectionValue("redis_connstr:master_conn"); //redis 实例名 option.InstanceName = "Test"; }); //注入Session模块 services.AddSession(option => { option.IdleTimeout = TimeSpan.FromMinutes(Convert.ToDouble(ConfigHelper.GetSectionValue("Session_Timeout"))); }); //注入Session调用模块 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); }
6.在Configure方法中配置如下:
// 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(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseSession();//增加 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
7.使用session前导入命名空间using Microsoft.AspNetCore.Http,使用如下代码:
public IActionResult Index() { HttpContext.Session.SetString("sa", "123"); return View(); } public IActionResult About() { var sa= HttpContext.Session.GetString("sa"); ViewData["Message"] = "Your application description page."; return View(); }
8.使用redis客户端可以看到你所存的session的值,如图所示
以上就是全部的实现步骤