netcore 使用redis session 分布式共享
- 首先准备redis服务器(docker 和redis3.0内置的哨兵进行高可用设置)
- 网站配置Redis作为存储session的介质(配置文件这些略)。然后可以了解一下MachineKey这个东西.(MachineKey是用来生成session和解密session的一个xml格式对象)
- 生成MachineKey
再startup config里面配置如下代码 //抽取key-xxxxx.xml services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"D:\")); 然后再对应的磁盘路径上面找到格式后缀为xml的文件
- 将文件用记事本打开,然后新增一个类来替换网站默认使用的MachineKey。
using Microsoft.AspNetCore.DataProtection.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace Session02 { public class CustomXmlRepository : IXmlRepository { /// <summary> /// 设置MachineKey这里的内容就是复制出xml文件的内容 /// </summary> private readonly string keyContent = @"<?xml version='1.0' encoding='utf-8'?> <key id='6e0d77ae-807d-4dd5-9b33-1f364f6c1f3e' version='1'> <creationDate>2018-07-25T07:01:39.5356164Z</creationDate> <activationDate>2018-07-25T07:01:39.4800644Z</activationDate> <expirationDate>2018-10-23T07:01:39.4800644Z</expirationDate> <descriptor deserializerType='Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'> <descriptor> <encryption algorithm='AES_256_CBC' /> <validation algorithm='HMACSHA256' /> <masterKey p4:requiresEncryption='true' xmlns:p4='http://schemas.asp.net/2015/03/dataProtection'> <!-- Warning: the key below is in an unencrypted form. --> <value>lPUxFutB30oi1KU990Y5nKxeCBnHg7h1JX26nvDlpxdbYciXQr2gdUpLxrL52O/vg8Htrr9F3Xf2fqnVhhAjhw==</value> </masterKey> </descriptor> </descriptor> </key>"; public virtual IReadOnlyCollection<XElement> GetAllElements() { return GetAllElementsCore().ToList().AsReadOnly(); } private IEnumerable<XElement> GetAllElementsCore() { yield return XElement.Parse(keyContent); } public virtual void StoreElement(XElement element, string friendlyName) { if (element == null) { throw new ArgumentNullException(nameof(element)); } StoreElementCore(element, friendlyName); } private void StoreElementCore(XElement element, string filename) { } } }
- 在startup里面注入CustomXmlRepository使用默认的key来生成session
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Session02 { 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) { //抽取key-xxxxx.xml //services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"D:\")); services.AddSingleton<IXmlRepository, CustomXmlRepository>(); services.AddDataProtection(configure => { configure.ApplicationDiscriminator = "Seesion.testweb"; }); services.AddDistributedRedisCache(option => { //redis 数据库连接字符串 option.Configuration = Configuration.GetConnectionString("RedisConnection"); //redis 实例名 option.InstanceName = "test"; }); services.AddSession(); services.AddMvc(); } // 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.UseSession(); app.UseMvc(); } } }
- 多个网站都用以上方法进行配置,然后测试一波
stay hungry stay foolish!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!