57 lines
2.1 KiB
C#
57 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using HuanMeng.MiaoYu.Code.DataAccess;
|
|
using HuanMeng.MiaoYu.Model.DbSqlServer.Db_MiaoYu;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
namespace HuanMeng.MiaoYu.Code.Cache
|
|
{
|
|
/// <summary>
|
|
/// 人物信息缓存
|
|
/// </summary>
|
|
public class CharacterInfoBaseCache
|
|
{
|
|
private IMemoryCache _memoryCache;
|
|
private object _cacheLock = new object(); // 用于线程安全的锁
|
|
private const string CharactersCacheKey = "Characters";
|
|
private DAO _dao;
|
|
|
|
public CharacterInfoBaseCache(IMemoryCache memoryCache, DAO dao)
|
|
{
|
|
this._memoryCache = memoryCache;
|
|
this._dao = dao;
|
|
}
|
|
|
|
public List<T_Character> GetCharacterFromCache(int userId)
|
|
{
|
|
lock (_cacheLock) // 加锁以防止并发访问
|
|
{
|
|
if (!_memoryCache.TryGetValue(CharactersCacheKey , out List<T_Character> cachedCharacter))
|
|
{
|
|
// 如果缓存中没有数据,则从数据库中获取
|
|
//var db = new YourDbContext();
|
|
var character = _dao.daoDbMiaoYu.context.T_Character.ToList();
|
|
if (character != null && character.Count > 0)
|
|
{
|
|
// 将数据放入缓存
|
|
var cacheEntryOptions = new MemoryCacheEntryOptions()
|
|
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30)) // 设置缓存过期时间
|
|
.SetSlidingExpiration(TimeSpan.FromMinutes(5)); // 设置滑动过期时间
|
|
_memoryCache.Set(CharactersCacheKey , character, cacheEntryOptions);
|
|
|
|
cachedCharacter = character;
|
|
}
|
|
else
|
|
{
|
|
cachedCharacter = new List<T_Character>();
|
|
}
|
|
}
|
|
return cachedCharacter;
|
|
}
|
|
}
|
|
}
|
|
}
|