using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Sog; using Sog.Service; using ProtoCSStruct; namespace Name { public class NameMsgHandler : BaseReloadableService { public override int GetServiceType() { return NameServiceType.NameMsgHandler; } //销毁 public override void Dispose() { } public void HandlerMessage(uint remoteAppID, MessageData message) { StructPacket packet; bool bSuccess = NameServerUtils.GetProtoPacker().UnpackMessage(message, out packet); if(bSuccess == false) { TraceLog.Error("HandlerMessage ,unpack msg failed {0}, remoteAppID {1}", message.Header.Type, remoteAppID); return; } //因为需要放入每个线程的队列,所以需要clone 一个新的对象,UnpackMessage出来的消息每次其实是同一个 //如果存在性能问题,可以根据消息类型进行缓冲 packet = packet.Clone(); //预先判断,提高效率 if (TraceLog.GetLogLevel() <= (int)Sog.Log.LogLevel.TraceDetail && TraceLog.IsSkipLogMsgID(packet.MsgID) == false) { TraceLog.TraceDetail("recv message from server {0}, message type {1} length {2} : {3}->{4}" , ServerIDUtils.IDToString(remoteAppID) , message.Header.Type , message.Header.Length , packet.MessageName() , packet.ToString()); } switch (packet.MsgID) { case (int)SSMsgID.NameQueryReq: OnQueryNameDBReq(remoteAppID, packet); break; case (int)SSMsgID.NameInsertReq: OnInsertNameDBReq(remoteAppID, packet); break; default: TraceLog.Error("NameMsgHandler unknow MsgID {0}", packet.MsgID); break; } } private int CalcTaskIndex(string hashName) { string strHash = NameUtils.CalcNameKey(hashName); int index = NameUtils.HashStringForIndex(strHash) % (int)MessageTaskDistributor.Instance.TaskCount; return index; } private int CalcRankTaskIndex(int realmId) { int index = 1 % (int)MessageTaskDistributor.Instance.TaskCount; return index; } private void OnQueryNameDBReq(uint remoteAppID, StructPacket packet) { ref SSNameQueryReq queryNameReq = ref packet.GetMessage(); string hashName = HashHelper.SHA1String(queryNameReq.StrName.GetString()); int iTaskIndex = CalcTaskIndex(hashName); //转给任务线程处理 MessageTaskDistributor.Instance.Distribute(remoteAppID, packet, iTaskIndex); return; } private void OnInsertNameDBReq(uint remoteAppID, StructPacket packet) { ref SSNameInsertReq insertNameReq = ref packet.GetMessage(); string hashName = HashHelper.SHA1String(insertNameReq.StrName.GetString()); int iTaskIndex = CalcTaskIndex(hashName); //转给任务线程处理 MessageTaskDistributor.Instance.Distribute(remoteAppID, packet, iTaskIndex); return; } } }