.Net Core添加分布式Session

一、Session

  HTTP是一个无状态协议,Web服务器将每一个请求都视为独立请求。并且不保存之前请求中用户的值。

  Session 状态是ASP.NET Core提供的一个功能,它可以在用户通应用访问网络服务器的时候保存和存储用户数据。ASP.NET Core通过包含Session ID的Cookie来维护会话状态,每个请求都会携带此Session ID。

  实现分布式Session方法官方提供有Redis、Sql Server等。但是Sql Server效率对于这种以key/value获取值的方式远远不及Redis效率高,所以这里选用Redis来作示例实现分布式Session。

二、安装Redis(Docker方式)

  2.1、新建一个Dockerfile和一个redis.conf

  

  Dockerfile内容:

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

  redis.conf内容:主要是启用密码登陆redis

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.1、构建docker镜像(docker build -t redis_test .)

  

  2.1、运行容器(docker run -d --restart=always -p 6379:6379 --name redis_container redis_test)

  

三、开始建立Core Demo

  3.1、新建2个MVC项目

   dotnet new mvc --name Session-demo-1

   dotnet new mvc --name Session-demo-2

  

 

  3.2、2个项目都添加(Microsoft.AspNetCore.DataProtection.Redis和Microsoft.Extensions.Caching.Redis)nuget包

  dotnet add package Microsoft.Extensions.Caching.Redis

  dotnet add package Microsoft.AspNetCore.DataProtection.Redis

  3.3、修改Startup.cs

  在ConfigureServices中添加:

        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

转载于:https://www.cnblogs.com/WJ--NET/p/10341702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core 中,可以使用 System.Timers.Timer 或 System.Threading.Timer 类来添加定时器。以下是两个类的使用示例: 1. System.Timers.Timer 类 ```csharp using System; using System.Timers; namespace TimerExample { class Program { static void Main(string[] args) { // 创建定时器 Timer timer = new Timer(1000); // 1 秒钟执行一次 // 设置定时器回调函数 timer.Elapsed += OnTimerElapsed; // 启动定时器 timer.Start(); // 等待用户输入 Console.ReadLine(); // 停止定时器 timer.Stop(); } static void OnTimerElapsed(object sender, ElapsedEventArgs e) { Console.WriteLine("Timer elapsed at {0:HH:mm:ss.fff}", e.SignalTime); } } } ``` 在上面的示例中,首先创建了一个 Timer 对象,并指定了定时器的时间间隔为 1 秒钟。然后设置了定时器的回调函数 OnTimerElapsed,该函数会在定时器时间间隔到达时被调用,输出当前时间。最后启动定时器并等待用户输入,当用户输入后停止定时器。 2. System.Threading.Timer 类 ```csharp using System; using System.Threading; namespace TimerExample { class Program { static Timer timer; static void Main(string[] args) { // 创建定时器 timer = new Timer(OnTimerElapsed, null, 0, 1000); // 1 秒钟执行一次 // 等待用户输入 Console.ReadLine(); // 停止定时器 timer.Dispose(); } static void OnTimerElapsed(object state) { Console.WriteLine("Timer elapsed at {0:HH:mm:ss.fff}", DateTime.Now); } } } ``` 在上面的示例中,首先创建了一个 Timer 对象,并指定了定时器的时间间隔为 1 秒钟。然后设置了定时器的回调函数 OnTimerElapsed,该函数会在定时器时间间隔到达时被调用,输出当前时间。最后启动定时器并等待用户输入,当用户输入后停止定时器。需要注意的是,System.Threading.Timer 的回调函数需要使用静态方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值