.Net Core添加分佈式Session

1、Session

  HTTP是一個無狀態協議,Web服務器將每個請求都視爲獨立請求。而且不保存以前請求中用戶的值。node

  Session 狀態是ASP.NET Core提供的一個功能,它能夠在用戶通應用訪問網絡服務器的時候保存和存儲用戶數據。ASP.NET Core經過包含Session ID的Cookie來維護會話狀態,每一個請求都會攜帶此Session ID。git

  實現分佈式Session方法官方提供有Redis、Sql Server等。可是Sql Server效率對於這種以key/value獲取值的方式遠遠不及Redis效率高,因此這裏選用Redis來做示例實現分佈式Session。github

2、安裝Redis(Docker方式)

  2.一、新建一個Dockerfile和一個redis.conf

  

  Dockerfile內容:redis

FROM redis
COPY redis.conf /usr/local/etc/redis/redis.conf
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]

  redis.conf內容:主要是啓用密碼登錄redisdocker

protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300
daemonize no
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile ""
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir ./
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
requirepass wangjun1234
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
slave-lazy-flush no
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble no
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
  2.一、構建docker鏡像(docker build -t redis_test .)

  

  2.一、運行容器(docker run -d --restart=always -p 6379:6379 --name redis_container redis_test)

  

3、開始創建Core Demo

  3.一、新建2個MVC項目

   dotnet new mvc --name Session-demo-1bash

   dotnet new mvc --name Session-demo-2服務器

  

 

  3.二、2個項目都添加(Microsoft.AspNetCore.DataProtection.Redis和Microsoft.Extensions.Caching.Redis)nuget包

  dotnet add package Microsoft.Extensions.Caching.Redis網絡

  dotnet add package Microsoft.AspNetCore.DataProtection.Redissession

  3.三、修改Startup.cs

  在ConfigureServices中添加:mvc

        public void ConfigureServices(IServiceCollection services)
        {
            //分佈式session
            var redis = ConnectionMultiplexer.Connect("47.107.30.29:6379,password=f***,defaultdatabase=7");
            services.AddDataProtection()
            .SetApplicationName("Test")
            .PersistKeysToRedis(redis, "Test-Keys");
            services.AddDistributedRedisCache(options => {
                options.Configuration = "47.107.30.29:6379,password=***,defaultdatabase=7";
                options.InstanceName = "session";
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            
          services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromHours(2);
            });
        }

  在Configure中添加

	app.UseSession();

  只配置Session-demo-1,同時啓動2個項目

  

  配置Session-demo-2(startup.cs的配置一摸同樣),同時啓動項目

  源碼:https://github.com/WangJunZzz/Core-Session.git

相關文章
相關標籤/搜索