我尝试缓存我的用户列表,这样当 200 个用户在线时,每 10 秒不会有 200 个数据库查询。
我有这个代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Business
{
public class UserList
{
private static object locker = new object();
public static List<DAL.OnlineList> userList;
public static DateTime date;
}
}
-
public static string GetOnlineList(HttpContext con)
{
List<DAL.OnlineList> onlineList = new List<DAL.OnlineList>();
if (Business.UserList.date == DateTime.MinValue || Business.UserList.date < DateTime.Now.AddSeconds(-30))
{
Business.UserList.date = DateTime.Now;
onlineList = DAL.UserDAL.GetAllOnlineUser().OrderBy(x => x.Username).ToList();
Business.UserList.userList = onlineList;
}
else
{
onlineList = Business.UserList.userList;
}
//Before
//List<DAL.OnlineList> onlineList = DAL.UserDAL.GetAllOnlineUser().OrderBy(x => x.Username).ToList();
}
每 10 秒从 WebMethod / pageMethod / JavaScript 调用调用 GetOnlineList 方法。所以之前是:200 个用户,每 10 秒 = 200 x 10 x 6 = 每分钟 12000 个数据库查询。
那么我的代码是对的,第一个用户将从数据库中加载列表并存储它——它会每 30 秒刷新一次——对吗?