自学内容网 自学内容网

asp.net core系统记录当前在线人数

实时记录当前在线人数,登录后保持120秒在线状态,在线状态保存在缓存中,采用滑动过期,在120秒内请求了系统,自动续活120秒;超过时间则移除用户在线状态;

  • 需要在登录过滤器标记用户在线状态
  • 需要排除循环请求的url,比如定时请求的待办数量
  • 登录成功后标记用户在线

web记录当前在线人数状态

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace WuZiFenGongSiInfomation.Models
{
    /// <summary>
    /// 当前在线人数
    /// </summary>
    /// 2024-12-26 9:57:09, wanghaoli
    public class OnlineUserAmount
    {
        static System.Collections.Concurrent.ConcurrentDictionary<string, bool> dict = new System.Collections.Concurrent.ConcurrentDictionary<string, bool>();

        /// <summary>
        /// 添加在线人
        /// </summary>
        /// <param name="userId">用户主键id</param>
        /// 2024-12-26 9:57:09, wanghaoli
        public static void AddUserOnline(string userId)
        {
            dict.TryAdd(userId, true);

            System.Runtime.Caching.MemoryCache.Default.AddOrGetExisting("AddUserOnline." + userId, 1, new CacheItemPolicy()
            {
                SlidingExpiration = TimeSpan.FromSeconds(120),
                RemovedCallback = (args) =>
                {
                    string userId2 = args.CacheItem.Key;
                    System.Diagnostics.Debug.WriteLine("移除用户在线状态 ,key=" + userId2);
                    LogHelpter.AddLog("移除用户在线状态,key=" + userId2, null, "UserOnline");

                    string userId3 = userId2.Replace("AddUserOnline.","");
                    bool removeResult = dict.TryRemove(userId3, out bool k);
                    if (removeResult)
                    {
                        System.Diagnostics.Debug.WriteLine("移除用户在线状态成功,key=" + userId2);
                        LogHelpter.AddLog("移除用户在线状态成功,key=" + userId2, null, "UserOnline");
                    }
                }
            });
        }


        /// <summary>
        /// 标记用户在线,续活
        /// </summary>
        /// <param name="userId"></param>
        /// 2024-12-26 10:04:09,   wanghaoli
        public static void VisitUseStatCache(string userId)
        {
            string key = "AddUserOnline." + userId;
            bool exists = System.Runtime.Caching.MemoryCache.Default.Contains(key);
            if (exists)
            {               
            }
            else
            {
                AddUserOnline(userId);
            }
            System.Diagnostics.Debug.WriteLine("激活用户在线状态,key=" + userId);
            LogHelpter.AddLog("激活用户在线状态,key=" + userId,null, "UserOnline");
        }

        /// <summary>
        /// 当前在线人数
        /// </summary>
        /// <returns></returns>
        public static int GetOnlineUserAmount()
        {
            return dict.Count;
        }
    }
}


原文地址:https://blog.csdn.net/u011511086/article/details/144739633

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!