CTT/Server/Hotfix/Game/System/Cache/PlayerInfoComponentSystem.cs

100 lines
3.3 KiB
C#

using System;
using System.Linq;
using ET.EventType;
using MongoDB.Bson;
using MongoDB.Driver;
namespace ET
{
public static class PlayerInfoComponentSystem
{
class PlayerInfoComponentStartSystem:StartSystem<PlayerInfoComponent>
{
public override void Start(PlayerInfoComponent self)
{
self.AddComponent<FixedTimeSaveComponent>().Init(3*60*1000,self.Save);
}
}
class ClearPerDay: AEvent<UpdatePer1DayOfMonth>
{
public override async ETTask Run(UpdatePer1DayOfMonth args)
{
PlayerInfoComponent playerInfoComponent = args.domain.GetComponent<PlayerInfoComponent>();
await playerInfoComponent.ClearAll();
}
}
public static void Save(this PlayerInfoComponent self)
{
Log.Info($"存档 「{self.unitInfoDic.Count}」");
Console.WriteLine("存档");
foreach (var kv in self.unitInfoDic)
{
DBComponent.Instance.Save(Game.IdGenerater.GenerateId(),kv.Value.Values.ToList()).Coroutine();
}
}
public static async ETTask ClearAll(this PlayerInfoComponent self)
{
Log.Info($"存档 「{self.unitInfoDic.Count}」");
using var listcomponent = ListComponent<ETTask>.Create();
foreach (var kv in self.unitInfoDic)
{
listcomponent.List.Add(DBComponent.Instance.Save(Game.IdGenerater.GenerateId(),kv.Value.Values.ToList()));
}
self.unitInfoDic.Clear();
await ETTaskHelper.WaitAll(listcomponent.List);
}
public static void AddInfo(this PlayerInfoComponent self, long id, string type, Entity str)
{
self.unitInfoDic.TryGetDic(type, out var dic);
if (dic == null)
{
self.unitInfoDic.Add(type, id, str);
return;
}
dic[id] = str;
}
public static async ETTask<Entity> GetInfo(this PlayerInfoComponent self, long id, string type)
{
self.unitInfoDic.TryGetDic(type, out var dic);
Entity entity = null;
if (dic == null)
{
entity = await GetEntity(id, type);
if (entity == null)
{
Log.Error($"e == null id = {id} type = {type}");
return null;
}
self.unitInfoDic.Add(type, id, entity);
dic = self.unitInfoDic[type];
}
dic.TryGetValue(id, out entity);
if (entity == null)
{
entity = await GetEntity(id, type);
if (entity == null)
{
Log.Error($"entity == null id = {id} type = {type}");
return null;
}
dic[id] = entity;
}
return entity;
}
private static async ETTask<Entity> GetEntity(long id, string type)
{
Log.Info($"{id} 从数据库查询 {type}");
var cursor = await DBComponent.Instance.GetCollection(type).FindAsync(d => d.Id == id);
Entity e = await cursor.FirstOrDefaultAsync();
return e;
}
}
}