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();
              }
          }
      }
    • 多个网站都用以上方法进行配置,然后测试一波
  • 相关阅读:
    第4月第1天 makefile automake
    第3月30天 UIImage imageWithContentsOfFile卡顿 Can't add self as subview MPMoviePlayerControlle rcrash
    第3月第27天 uitableviewcell复用
    learning uboot fstype command
    learning uboot part command
    linux command dialog
    linux command curl and sha256sum implement download verification package
    learning shell script prompt to run with superuser privileges (4)
    learning shell get script absolute path (3)
    learning shell args handing key=value example (2)
  • 原文地址:https://www.cnblogs.com/chongyao/p/9375590.html
Copyright © 2011-2022 走看看