zoukankan      html  css  js  c++  java
  • 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();
              }
          }
      }
    • 多个网站都用以上方法进行配置,然后测试一波
  • 相关阅读:
    JS定义一个立即执行的可重用函数
    Git常用命令速记与入门
    设计的一些kubernetes面试题
    运维知识各种链接
    php7.2安装smbclient扩展
    logrotate自定义切割时间的一些坑
    【转】日志收集工具scribe
    ELK日志报警插件ElastAlert并配置钉钉报警
    consul-server集群搭建
    加油,骚年
  • 原文地址:https://www.cnblogs.com/chongyao/p/9375590.html
Copyright © 2011-2022 走看看