tanghai 6 жил өмнө
parent
commit
c037aacbc1
100 өөрчлөгдсөн 2688 нэмэгдсэн , 4195 устгасан
  1. 1 1
      Book/Example/Example2_1/Example2_1.csproj
  2. 1 1
      Book/Example/Example2_2/Example2_2.csproj
  3. 1 1
      Book/Example/Example2_2_2/Example2_2_2.csproj
  4. 1 1
      Book/Example/Example2_3/Example2_3.csproj
  5. 1 1
      Book/Example/Example2_3_2/Example2_3_2.csproj
  6. 1 1
      Book/Example/Example3_5/Example3_5.csproj
  7. 1188 2307
      FileServer/FileServer.deps.json
  8. BIN
      FileServer/FileServer.dll
  9. BIN
      FileServer/FileServer.pdb
  10. 2 3
      FileServer/FileServer.runtimeconfig.dev.json
  11. 2 2
      FileServer/FileServer.runtimeconfig.json
  12. 37 110
      Proto/InnerMessage.proto
  13. 3 3
      Proto/Proto2CS.deps.json
  14. BIN
      Proto/Proto2CS.dll
  15. BIN
      Proto/Proto2CS.pdb
  16. 2 3
      Proto/Proto2CS.runtimeconfig.dev.json
  17. 2 2
      Proto/Proto2CS.runtimeconfig.json
  18. 31 44
      Server/App/NLog.config
  19. 56 121
      Server/App/Program.cs
  20. 1 1
      Server/App/Server.App.csproj
  21. 1 1
      Server/Hotfix/Handler/C2G_PlayerInfoHandler.cs
  22. 14 14
      Server/Hotfix/Handler/C2M_ReloadHandler.cs
  23. 1 1
      Server/Hotfix/Handler/C2R_PingHandler.cs
  24. 1 1
      Server/Hotfix/Handler/G2C_TestHandler.cs
  25. 1 1
      Server/Hotfix/Handler/M2A_ReloadHandler.cs
  26. 17 22
      Server/Hotfix/Module/Actor/ActorMessageDispatcherComponentSystem.cs
  27. 128 0
      Server/Hotfix/Module/Actor/ActorMessageSenderComponentSystem.cs
  28. 0 28
      Server/Hotfix/Module/Actor/ActorMessageSenderHelper.cs
  29. 2 24
      Server/Hotfix/Module/Actor/MailBoxComponentSystem.cs
  30. 16 15
      Server/Hotfix/Module/Actor/MailboxDispatcherComponentSystem.cs
  31. 1 1
      Server/Hotfix/Module/Actor/MailboxGateSessionHandler.cs
  32. 2 3
      Server/Hotfix/Module/Actor/MailboxMessageDispatcherHandler.cs
  33. 67 31
      Server/Hotfix/Module/ActorLocation/ActorLocationSenderComponentSystem.cs
  34. 103 98
      Server/Hotfix/Module/ActorLocation/ActorLocationSenderSystem.cs
  35. 34 16
      Server/Hotfix/Module/ActorLocation/LocationProxyComponentSystem.cs
  36. 4 4
      Server/Hotfix/Module/ActorLocation/ObjectAddRequestHandler.cs
  37. 4 4
      Server/Hotfix/Module/ActorLocation/ObjectGetRequestHandler.cs
  38. 4 4
      Server/Hotfix/Module/ActorLocation/ObjectLockRequestHandler.cs
  39. 4 4
      Server/Hotfix/Module/ActorLocation/ObjectRemoveRequestHandler.cs
  40. 4 4
      Server/Hotfix/Module/ActorLocation/ObjectUnLockRequestHandler.cs
  41. 1 16
      Server/Hotfix/Module/Config/ConfigComponentSystem.cs
  42. 270 0
      Server/Hotfix/Module/DB/DBComponentSystem.cs
  43. 0 172
      Server/Hotfix/Module/DB/DBProxyComponentSystem.cs
  44. 0 17
      Server/Hotfix/Module/DB/DBQueryBatchRequestHandler.cs
  45. 0 19
      Server/Hotfix/Module/DB/DBQueryJsonRequestHandler.cs
  46. 0 18
      Server/Hotfix/Module/DB/DBQueryRequestHandler.cs
  47. 0 23
      Server/Hotfix/Module/DB/DBSaveBatchRequestHandler.cs
  48. 0 21
      Server/Hotfix/Module/DB/DBSaveRequestHandler.cs
  49. 26 32
      Server/Hotfix/Module/Demo/Actor_TransferHandler.cs
  50. 5 4
      Server/Hotfix/Module/Demo/C2G_EnterMapHandler.cs
  51. 3 3
      Server/Hotfix/Module/Demo/C2G_LoginGateHandler.cs
  52. 3 3
      Server/Hotfix/Module/Demo/C2R_LoginHandler.cs
  53. 9 8
      Server/Hotfix/Module/Demo/G2M_CreateUnitHandler.cs
  54. 4 5
      Server/Hotfix/Module/Demo/M2M_TrasferUnitRequest.cs
  55. 62 19
      Server/Hotfix/Module/Demo/MessageHelper.cs
  56. 4 4
      Server/Hotfix/Module/Demo/R2G_GetLoginKeyHandler.cs
  57. 0 30
      Server/Hotfix/Module/Demo/RealmGateAddressComponentSystem.cs
  58. 16 0
      Server/Hotfix/Module/Demo/RealmGateAddressHelper.cs
  59. 1 2
      Server/Hotfix/Module/Demo/SessionPlayerComponentSystem.cs
  60. 4 4
      Server/Hotfix/Module/Demo/UnitPathComponentSystem.cs
  61. 32 80
      Server/Hotfix/Module/Message/InnerMessageDispatcher.cs
  62. 75 0
      Server/Hotfix/Module/Message/InnerMessageDispatcherHelper.cs
  63. 13 16
      Server/Hotfix/Module/Message/MessageDispatherComponentSystem.cs
  64. 0 2
      Server/Hotfix/Module/Message/NetInnerComponentSystem.cs
  65. 6 9
      Server/Hotfix/Module/Message/OuterMessageDispatcher.cs
  66. 22 0
      Server/Hotfix/Module/Scene/AfterScenesAdd_CreateScene.cs
  67. 41 0
      Server/Hotfix/Module/Scene/SceneFactory.cs
  68. 1 1
      Server/Hotfix/Server.Hotfix.csproj
  69. 1 0
      Server/Model/Base/Event/EventIdType.cs
  70. 6 0
      Server/Model/Base/Object/IDBCollection.cs
  71. 0 98
      Server/Model/Component/AppManagerComponent.cs
  72. 1 1
      Server/Model/Component/KVComponent.cs
  73. 1 1
      Server/Model/Component/OptionComponent.cs
  74. 2 2
      Server/Model/Component/ReplComponent.cs
  75. 1 1
      Server/Model/Component/RobotComponent.cs
  76. 169 141
      Server/Model/Component/StartConfigComponent.cs
  77. 5 16
      Server/Model/Entity/Game.cs
  78. 22 8
      Server/Model/Entity/Scene.cs
  79. 3 12
      Server/Model/Module/Actor/ActorMessageDispatcherComponent.cs
  80. 7 7
      Server/Model/Module/Actor/ActorMessageSender.cs
  81. 13 13
      Server/Model/Module/Actor/ActorMessageSenderComponent.cs
  82. 3 21
      Server/Model/Module/Actor/MailBoxComponent.cs
  83. 4 13
      Server/Model/Module/Actor/MailboxDispatcherComponent.cs
  84. 2 5
      Server/Model/Module/Actor/MailboxHandlerAttribute.cs
  85. 6 5
      Server/Model/Module/Actor/MailboxType.cs
  86. 11 24
      Server/Model/Module/ActorLocation/ActorLocationSender.cs
  87. 9 48
      Server/Model/Module/ActorLocation/ActorLocationSenderComponent.cs
  88. 0 12
      Server/Model/Module/ActorLocation/Location.cs
  89. 55 55
      Server/Model/Module/ActorLocation/LocationComponent.cs
  90. 14 2
      Server/Model/Module/ActorLocation/LocationProxyComponent.cs
  91. 1 1
      Server/Model/Module/Benchmark/BenchmarkComponent.cs
  92. 1 1
      Server/Model/Module/Benchmark/WebSocketBenchmarkComponent.cs
  93. 1 1
      Server/Model/Module/Config/ConfigComponent.cs
  94. 14 78
      Server/Model/Module/DB/DBComponent.cs
  95. 0 14
      Server/Model/Module/DB/DBProxyComponent.cs
  96. 0 54
      Server/Model/Module/DB/DBQueryBatchTask.cs
  97. 0 43
      Server/Model/Module/DB/DBQueryJsonTask.cs
  98. 0 38
      Server/Model/Module/DB/DBQueryTask.cs
  99. 0 52
      Server/Model/Module/DB/DBSaveBatchTask.cs
  100. 0 42
      Server/Model/Module/DB/DBSaveTask.cs

+ 1 - 1
Book/Example/Example2_1/Example2_1.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
         <RootNamespace>Example1._1</RootNamespace>
     </PropertyGroup>
 

+ 1 - 1
Book/Example/Example2_2/Example2_2.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
 
     <ItemGroup>

+ 1 - 1
Book/Example/Example2_2_2/Example2_2_2.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
 
     <ItemGroup>

+ 1 - 1
Book/Example/Example2_3/Example2_3.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
 
 </Project>

+ 1 - 1
Book/Example/Example2_3_2/Example2_3_2.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
 
 </Project>

+ 1 - 1
Book/Example/Example3_5/Example3_5.csproj

@@ -2,7 +2,7 @@
 
     <PropertyGroup>
         <OutputType>Exe</OutputType>
-        <TargetFramework>netcoreapp2.2</TargetFramework>
+        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
 
     <ItemGroup>

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 1188 - 2307
FileServer/FileServer.deps.json


BIN
FileServer/FileServer.dll


BIN
FileServer/FileServer.pdb


+ 2 - 3
FileServer/FileServer.runtimeconfig.dev.json

@@ -1,9 +1,8 @@
 {
   "runtimeOptions": {
     "additionalProbingPaths": [
-      "C:\\Users\\USER-PC\\.dotnet\\store\\|arch|\\|tfm|",
-      "C:\\Users\\USER-PC\\.nuget\\packages",
-      "C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
+      "/Users/tanghai/.dotnet/store/|arch|/|tfm|",
+      "/Users/tanghai/.nuget/packages"
     ]
   }
 }

+ 2 - 2
FileServer/FileServer.runtimeconfig.json

@@ -1,9 +1,9 @@
 {
   "runtimeOptions": {
-    "tfm": "netcoreapp2.1",
+    "tfm": "netcoreapp3.0",
     "framework": {
       "name": "Microsoft.AspNetCore.App",
-      "version": "2.1.1"
+      "version": "3.0.0"
     },
     "configProperties": {
       "System.GC.Server": true

+ 37 - 110
Proto/InnerMessage.proto

@@ -4,13 +4,14 @@ package ETModel;
 /// <summary>
 /// 传送unit
 /// </summary>
-message M2M_TrasferUnitRequest // IRequest
+message M2M_TrasferUnitRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     Unit Unit = 1;
 }
 
-message M2M_TrasferUnitResponse // IResponse
+message M2M_TrasferUnitResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
@@ -19,189 +20,113 @@ message M2M_TrasferUnitResponse // IResponse
     int64 InstanceId = 1;
 }
 
-message M2A_Reload // IRequest
+message M2A_Reload // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
 }
 
-message A2M_Reload // IResponse
+message A2M_Reload // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message G2G_LockRequest // IRequest
+message G2G_LockRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Id = 1;
     string Address = 2;
 }
 
-message G2G_LockResponse // IResponse
+message G2G_LockResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message G2G_LockReleaseRequest // IRequest
+message G2G_LockReleaseRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Id = 1;
     string Address = 2;
 }
 
-message G2G_LockReleaseResponse // IResponse
+message G2G_LockReleaseResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message DBSaveRequest // IRequest
-{
-    int32 RpcId = 90;
-
-    string CollectionName = 1;
-    ComponentWithId Component = 2;
-}
-
-
-message DBSaveBatchResponse // IResponse
-{
-    int32 RpcId = 90;
-    int32 Error = 91;
-    string Message = 92;
-}
-
-message DBSaveBatchRequest // IRequest
-{
-    int32 RpcId = 90;
-
-    string CollectionName = 1;
-    repeated ComponentWithId Components = 2;
-}
-
-message DBSaveResponse // IResponse
-{
-    int32 RpcId = 90;
-    int32 Error = 91;
-    string Message = 92;
-}
-
-message DBQueryRequest // IRequest
-{
-    int32 RpcId = 90;
-    int64 Id = 1;
-    string CollectionName = 2;
-}
-
-message DBQueryResponse // IResponse
-{
-    int32 RpcId = 90;
-    int32 Error = 91;
-    string Message = 92;
-
-    ComponentWithId Component = 1;
-}
-
-message DBQueryBatchRequest // IRequest
-{
-    int32 RpcId = 90;
-    string CollectionName = 1;
-    repeated int64 IdList = 2;
-}
-
-message DBQueryBatchResponse // IResponse
-{
-    int32 RpcId = 90;
-    int32 Error = 91;
-    string Message = 92;
-
-    repeated ComponentWithId Components = 1;
-}
-
-message DBQueryJsonRequest // IRequest
-{
-    int32 RpcId = 90;
-    string CollectionName = 1;
-    string Json = 2;
-}
-
-message DBQueryJsonResponse // IResponse
-{
-    int32 RpcId = 90;
-    int32 Error = 91;
-    string Message = 92;
-
-    repeated ComponentWithId Components = 1;
-}
-
-message ObjectAddRequest // IRequest
+message ObjectAddRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Key = 1;
     int64 InstanceId = 2;
 }
 
-message ObjectAddResponse // IResponse
+message ObjectAddResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
-
-message ObjectRemoveRequest // IRequest
+message ObjectLockRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Key = 1;
+    int64 InstanceId = 2;
+    int32 Time = 3;
 }
-
-message ObjectRemoveResponse // IResponse
+message ObjectLockResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message ObjectLockRequest // IRequest
+message ObjectUnLockRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Key = 1;
-    int64 InstanceId = 2;
-    int32 Time = 3;
+    int64 OldInstanceId = 2;
+    int64 InstanceId = 3;
 }
-
-message ObjectLockResponse // IResponse
+message ObjectUnLockResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message ObjectUnLockRequest // IRequest
+message ObjectRemoveRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Key = 1;
-    int64 OldInstanceId = 2;
-    int64 InstanceId = 3;
 }
-
-message ObjectUnLockResponse // IResponse
+message ObjectRemoveResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
     string Message = 92;
 }
 
-message ObjectGetRequest // IRequest
+message ObjectGetRequest // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 Key = 1;
 }
-
-message ObjectGetResponse // IResponse
+message ObjectGetResponse // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
@@ -210,13 +135,14 @@ message ObjectGetResponse // IResponse
     int64 InstanceId = 1;
 }
 
-message R2G_GetLoginKey // IRequest
+message R2G_GetLoginKey // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     string Account = 1;
 }
 
-message G2R_GetLoginKey // IResponse
+message G2R_GetLoginKey // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;
@@ -225,14 +151,15 @@ message G2R_GetLoginKey // IResponse
     int64 Key = 1;
 }
 
-message G2M_CreateUnit // IRequest
+message G2M_CreateUnit // IActorRequest
 {
     int32 RpcId = 90;
+    int64 ActorId = 93;
     int64 PlayerId = 1;
     int64 GateSessionId = 2;
 }
 
-message M2G_CreateUnit // IResponse
+message M2G_CreateUnit // IActorResponse
 {
     int32 RpcId = 90;
     int32 Error = 91;

+ 3 - 3
Proto/Proto2CS.deps.json

@@ -1,11 +1,11 @@
 {
   "runtimeTarget": {
-    "name": ".NETCoreApp,Version=v2.1",
-    "signature": "da39a3ee5e6b4b0d3255bfef95601890afd80709"
+    "name": ".NETCoreApp,Version=v3.0",
+    "signature": ""
   },
   "compilationOptions": {},
   "targets": {
-    ".NETCoreApp,Version=v2.1": {
+    ".NETCoreApp,Version=v3.0": {
       "Proto2CS/1.0.0": {
         "runtime": {
           "Proto2CS.dll": {}

BIN
Proto/Proto2CS.dll


BIN
Proto/Proto2CS.pdb


+ 2 - 3
Proto/Proto2CS.runtimeconfig.dev.json

@@ -1,9 +1,8 @@
 {
   "runtimeOptions": {
     "additionalProbingPaths": [
-      "C:\\Users\\USER-PC\\.dotnet\\store\\|arch|\\|tfm|",
-      "C:\\Users\\USER-PC\\.nuget\\packages",
-      "C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
+      "/Users/tanghai/.dotnet/store/|arch|/|tfm|",
+      "/Users/tanghai/.nuget/packages"
     ]
   }
 }

+ 2 - 2
Proto/Proto2CS.runtimeconfig.json

@@ -1,9 +1,9 @@
 {
   "runtimeOptions": {
-    "tfm": "netcoreapp2.1",
+    "tfm": "netcoreapp3.0",
     "framework": {
       "name": "Microsoft.NETCore.App",
-      "version": "2.1.0"
+      "version": "3.0.0"
     }
   }
 }

+ 31 - 44
Server/App/NLog.config

@@ -1,70 +1,57 @@
 <?xml version="1.0" encoding="utf-8" ?>
 
 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-	<variable name="appType" value="" />
-	<variable name="appId" value="" />
 	<targets>
-		<target name="all" xsi:type="File"
-			fileName="${basedir}/../Logs/Log.txt"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
+		<target name="debug" xsi:type="File"
+				openFileCacheTimeout="3600"
+				fileName="${basedir}/../Logs/Log-${var:appIdFormat}-${date:universalTime=true:format=yyyyMMdd}-Debug.log"
+				deleteOldFileOnStartup="false"
+				layout="${longdate} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
 	</targets>
 
 	<targets>
-		<target name="trace" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Trace-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${message} ${newline} ${stacktrace:format=Raw:topFrames=10:skipFrames=0}" />
+		<target name="info" xsi:type="File"
+				openFileCacheTimeout="3600"
+				fileName="${basedir}/../Logs/Log-${var:appIdFormat}-${date:universalTime=true:format=yyyyMMdd}-Info.log"
+				deleteOldFileOnStartup="false"
+				layout="${longdate} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
 	</targets>
-	
+
 	<targets>
-		<target name="debug" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Debug-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
+		<target name="error" xsi:type="File"
+				openFileCacheTimeout="3600"
+				fileName="${basedir}/../Logs/Log-${var:appIdFormat}-${date:universalTime=true:format=yyyyMMdd}-Error.log"
+				deleteOldFileOnStartup="false"
+				layout="${longdate} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
 	</targets>
 
 	<targets>
-		<target name="info" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Info-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
+		<target name="errorConsole" xsi:type="Console"
+				layout="${longdate} ${callsite:className=false:methodName=false:fileName=true:includeSourcePath=false:skipFrames=2} ${message}" />
 	</targets>
-	
+
 	<targets>
-		<target name="error" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Error-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${message} ${newline} ${stacktrace:format=Raw:topFrames=10:skipFrames=0}" />
-	</targets>
-  
-  <targets>
 		<target name="warn" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Warning-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${message}" />
+				openFileCacheTimeout="3600"
+				fileName="${basedir}/../Logs/Log-${var:appIdFormat}-${date:universalTime=true:format=yyyyMMdd}-Warning.log"
+				deleteOldFileOnStartup="false"
+				layout="${longdate} ${message}" />
 	</targets>
-  
-  <targets>
+
+	<targets>
 		<target name="fatal" xsi:type="File"
-			openFileCacheTimeout="3600"
-			fileName="${basedir}/../Logs/Log-${var:appType}-${var:appIdFormat}-Fatal-${date:universalTime=true:format=yyyyMMdd}.log"
-			deleteOldFileOnStartup="false"
-			layout="${longdate} ${var:appTypeFormat} ${var:appIdFormat} ${message} ${newline} ${stacktrace:format=Raw:topFrames=10:skipFrames=0}" />
+				openFileCacheTimeout="3600"
+				fileName="${basedir}/../Logs/Log-${var:appIdFormat}-${date:universalTime=true:format=yyyyMMdd}-Fatal.log"
+				deleteOldFileOnStartup="false"
+				layout="${longdate} ${message} ${newline} ${stacktrace:format=Raw:topFrames=10:skipFrames=2}" />
 	</targets>
-	
+
 	<rules>
-		<!--<logger name="*" minlevel="Trace" writeTo="all" />-->
-		<logger name="*" minlevel="Trace" maxlevel="Trace" writeTo="trace" />
 		<logger name="*" minlevel="Trace" maxlevel="Fatal" writeTo="debug" />
 		<logger name="*" minlevel="Info" maxlevel="Info" writeTo="info" />
 		<logger name="*" minlevel="Warn" maxlevel="Warn" writeTo="warn" />
 		<logger name="*" minlevel="Error" maxlevel="Error" writeTo="error" />
+		<logger name="*" minlevel="Error" maxlevel="Error" writeTo="errorConsole" />
 		<logger name="*" minlevel="Fatal" maxlevel="Fatal" writeTo="fatal" />
 	</rules>
 </nlog>

+ 56 - 121
Server/App/Program.cs

@@ -1,9 +1,11 @@
 using System;
+using System.Diagnostics;
+using System.IO;
 using System.Threading;
-using ETModel;
+using CommandLine;
 using NLog;
 
-namespace App
+namespace ETModel
 {
 	internal static class Program
 	{
@@ -13,140 +15,73 @@ namespace App
 			SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);
 			
 			try
-			{			
+			{		
 				Game.EventSystem.Add(DLLType.Model, typeof(Game).Assembly);
 				Game.EventSystem.Add(DLLType.Hotfix, DllHelper.GetHotfixAssembly());
+				
+				MongoHelper.Init();
+				
+				// 命令行参数
+				Parser.Default.ParseArguments<Options>(args)
+						.WithNotParsed(error => throw new Exception($"命令行格式错误!"))
+						.WithParsed(o => { Game.Options = o; });
 
-				Options options = Game.Scene.AddComponent<OptionComponent, string[]>(args).Options;
-				StartConfig startConfig = Game.Scene.AddComponent<StartConfigComponent, string, int>(options.Config, options.AppId).StartConfig;
-
-				if (!options.AppType.Is(startConfig.AppType))
-				{
-					Log.Error("命令行参数apptype与配置不一致");
-					return;
-				}
-
-				IdGenerater.AppId = options.AppId;
+				IdGenerater.AppId = Game.Options.Id;
+				
+				// 启动配置
+				StartConfig allConfig = MongoHelper.FromJson<StartConfig>(File.ReadAllText(Path.Combine("../Config/StartConfig/", Game.Options.Config)));
 
-				LogManager.Configuration.Variables["appType"] = $"{startConfig.AppType}";
-				LogManager.Configuration.Variables["appId"] = $"{startConfig.AppId}";
-				LogManager.Configuration.Variables["appTypeFormat"] = $"{startConfig.AppType, -8}";
-				LogManager.Configuration.Variables["appIdFormat"] = $"{startConfig.AppId:0000}";
+				StartConfig startConfig = allConfig.Get(Game.Options.Id);
+				Game.Scene = EntityFactory.CreateScene(0, "Process", SceneType.Process);
+				
+				LogManager.Configuration.Variables["appIdFormat"] = $"{Game.Scene.Id:0000}";
+				
+				Game.Scene.AddComponent<StartConfigComponent, StartConfig, long>(allConfig, startConfig.Id);
 
-				Log.Info($"server start........................ {startConfig.AppId} {startConfig.AppType}");
+				Log.Info($"server start........................ {Game.Scene.Id}");
 
 				Game.Scene.AddComponent<TimerComponent>();
 				Game.Scene.AddComponent<OpcodeTypeComponent>();
 				Game.Scene.AddComponent<MessageDispatcherComponent>();
+				Game.Scene.AddComponent<ConfigComponent>();
+				Game.Scene.AddComponent<CoroutineLockComponent>();
+				// 发送普通actor消息
+				Game.Scene.AddComponent<ActorMessageSenderComponent>();
+				// 发送location actor消息
+				Game.Scene.AddComponent<ActorLocationSenderComponent>();
+				// 访问location server的组件
+				Game.Scene.AddComponent<LocationProxyComponent>();
+				// 这两个组件是处理actor消息使用的
+				Game.Scene.AddComponent<MailboxDispatcherComponent>();
+				Game.Scene.AddComponent<ActorMessageDispatcherComponent>();
+				// manager server组件,用来管理其它进程使用
+				Game.Scene.AddComponent<NumericWatcherComponent>();
+				Game.Scene.AddComponent<ConsoleComponent>();
 
-				// 根据不同的AppType添加不同的组件
-				OuterConfig outerConfig = startConfig.GetComponent<OuterConfig>();
-				InnerConfig innerConfig = startConfig.GetComponent<InnerConfig>();
-				ClientConfig clientConfig = startConfig.GetComponent<ClientConfig>();
+
+                OuterConfig outerConfig = startConfig.GetComponent<OuterConfig>();
+				if (outerConfig != null)
+				{
+					// 外网消息组件
+					Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
+				}
 				
-				switch (startConfig.AppType)
+				InnerConfig innerConfig = startConfig.GetComponent<InnerConfig>();
+				if (innerConfig != null)
 				{
-					case AppType.Manager:
-						Game.Scene.AddComponent<AppManagerComponent>();
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
-						break;
-					case AppType.Realm:
-						Game.Scene.AddComponent<MailboxDispatcherComponent>();
-						Game.Scene.AddComponent<ActorMessageDispatcherComponent>();
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
-						Game.Scene.AddComponent<LocationProxyComponent>();
-						Game.Scene.AddComponent<RealmGateAddressComponent>();
-						break;
-					case AppType.Gate:
-						Game.Scene.AddComponent<PlayerComponent>();
-						Game.Scene.AddComponent<MailboxDispatcherComponent>();
-						Game.Scene.AddComponent<ActorMessageDispatcherComponent>();
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
-						Game.Scene.AddComponent<LocationProxyComponent>();
-						Game.Scene.AddComponent<ActorMessageSenderComponent>();
-						Game.Scene.AddComponent<ActorLocationSenderComponent>();
-						Game.Scene.AddComponent<GateSessionKeyComponent>();
-						Game.Scene.AddComponent<CoroutineLockComponent>();
-						break;
-					case AppType.Location:
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						Game.Scene.AddComponent<LocationComponent>();
-						Game.Scene.AddComponent<CoroutineLockComponent>();
-						break;
-					case AppType.Map:
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						Game.Scene.AddComponent<UnitComponent>();
-						Game.Scene.AddComponent<LocationProxyComponent>();
-						Game.Scene.AddComponent<ActorMessageSenderComponent>();
-						Game.Scene.AddComponent<ActorLocationSenderComponent>();
-						Game.Scene.AddComponent<MailboxDispatcherComponent>();
-						Game.Scene.AddComponent<ActorMessageDispatcherComponent>();
-						Game.Scene.AddComponent<PathfindingComponent>();
-						Game.Scene.AddComponent<CoroutineLockComponent>();
-						break;
-					case AppType.AllServer:
-						// 发送普通actor消息
-						Game.Scene.AddComponent<ActorMessageSenderComponent>();
-						
-						// 发送location actor消息
-						Game.Scene.AddComponent<ActorLocationSenderComponent>();
-						
-						//Game.Scene.AddComponent<DBComponent>();
-						//Game.Scene.AddComponent<DBProxyComponent>();
-						
-						// location server需要的组件
-						Game.Scene.AddComponent<LocationComponent>();
-						
-						// 访问location server的组件
-						Game.Scene.AddComponent<LocationProxyComponent>();
-						
-						// 这两个组件是处理actor消息使用的
-						Game.Scene.AddComponent<MailboxDispatcherComponent>();
-						Game.Scene.AddComponent<ActorMessageDispatcherComponent>();
-						
-						// 内网消息组件
-						Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
-						
-						// 外网消息组件
-						Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
-						
-						// manager server组件,用来管理其它进程使用
-						Game.Scene.AddComponent<AppManagerComponent>();
-						Game.Scene.AddComponent<RealmGateAddressComponent>();
-						Game.Scene.AddComponent<GateSessionKeyComponent>();
-						
-						// 配置管理
-						Game.Scene.AddComponent<ConfigComponent>();
-						
-						// recast寻路组件
-						Game.Scene.AddComponent<PathfindingComponent>();
-						
-						Game.Scene.AddComponent<PlayerComponent>();
-						Game.Scene.AddComponent<UnitComponent>();
-
-						Game.Scene.AddComponent<ConsoleComponent>();
+					// 内网消息组件
+					Game.Scene.AddComponent<NetInnerComponent, string>(innerConfig.Address);
+				}
 
-						Game.Scene.AddComponent<CoroutineLockComponent>();
-						// Game.Scene.AddComponent<HttpComponent>();
-						break;
-					case AppType.Benchmark:
-						Game.Scene.AddComponent<NetOuterComponent>();
-						Game.Scene.AddComponent<BenchmarkComponent, string>(clientConfig.Address);
-						break;
-					case AppType.BenchmarkWebsocketServer:
-						Game.Scene.AddComponent<NetOuterComponent, string>(outerConfig.Address);
-						break;
-					case AppType.BenchmarkWebsocketClient:
-						Game.Scene.AddComponent<NetOuterComponent>();
-						Game.Scene.AddComponent<WebSocketBenchmarkComponent, string>(clientConfig.Address);
-						break;
-					default:
-						throw new Exception($"命令行参数没有设置正确的AppType: {startConfig.AppType}");
+				DBConfig dbConfig = startConfig.GetComponent<DBConfig>();
+				if (dbConfig != null)
+				{
+					Game.Scene.AddComponent<DBComponent, DBConfig>(dbConfig);
 				}
 				
+				// 先加这里,后面删掉
+				Game.EventSystem.Run(EventIdType.AfterScenesAdd);
+				
 				while (true)
 				{
 					try

+ 1 - 1
Server/App/Server.App.csproj

@@ -2,7 +2,7 @@
 
   <PropertyGroup>
     <OutputType>Exe</OutputType>
-    <TargetFramework>netcoreapp2.2</TargetFramework>
+    <TargetFramework>netcoreapp3.0</TargetFramework>
     <AssemblyName>App</AssemblyName>
     <RootNamespace>App</RootNamespace>
     <LangVersion>7.3</LangVersion>

+ 1 - 1
Server/Hotfix/Handler/C2G_PlayerInfoHandler.cs

@@ -4,7 +4,7 @@ using ETModel;
 namespace ETHotfix
 {
 	// 用来测试消息包含复杂类型,是否产生gc
-	[MessageHandler(AppType.Gate)]
+	[MessageHandler]
 	public class C2G_PlayerInfoHandler : AMRpcHandler<C2G_PlayerInfo, G2C_PlayerInfo>
 	{
 		protected override async ETTask Run(Session session, C2G_PlayerInfo request, G2C_PlayerInfo response, Action reply)

+ 14 - 14
Server/Hotfix/Handler/C2M_ReloadHandler.cs

@@ -3,24 +3,24 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Manager)]
+	[MessageHandler]
 	public class C2M_ReloadHandler: AMRpcHandler<C2M_Reload, M2C_Reload>
 	{
 		protected override async ETTask Run(Session session, C2M_Reload request, M2C_Reload response, Action reply)
 		{
-			if (request.Account != "panda" && request.Password != "panda")
-			{
-				Log.Error($"error reload account and password: {MongoHelper.ToJson(request)}");
-				return;
-			}
-			StartConfigComponent startConfigComponent = Game.Scene.GetComponent<StartConfigComponent>();
-			NetInnerComponent netInnerComponent = Game.Scene.GetComponent<NetInnerComponent>();
-			foreach (StartConfig startConfig in startConfigComponent.GetAll())
-			{
-				InnerConfig innerConfig = startConfig.GetComponent<InnerConfig>();
-				Session serverSession = netInnerComponent.Get(innerConfig.IPEndPoint);
-				await serverSession.Call(new M2A_Reload());
-			}
+			//if (request.Account != "panda" && request.Password != "panda")
+			//{
+			//	Log.Error($"error reload account and password: {MongoHelper.ToJson(request)}");
+			//	return;
+			//}
+			//StartConfigComponent startConfigComponent = Game.Scene.GetComponent<StartConfigComponent>();
+			//NetInnerComponent netInnerComponent = Game.Scene.GetComponent<NetInnerComponent>();
+			//foreach (StartConfig startConfig in startConfigComponent.GetAll())
+			//{
+			//	InnerConfig innerConfig = startConfig.GetComponent<InnerConfig>();
+			//	Session serverSession = netInnerComponent.Get(innerConfig.IPEndPoint);
+			//	await serverSession.Call(new M2A_Reload());
+			//}
 			reply();
 		}
 	}

+ 1 - 1
Server/Hotfix/Handler/C2R_PingHandler.cs

@@ -3,7 +3,7 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.AllServer)]
+	[MessageHandler]
 	public class C2R_PingHandler : AMRpcHandler<C2R_Ping, R2C_Ping>
 	{
 		protected override async ETTask Run(Session session, C2R_Ping request, R2C_Ping response, Action reply)

+ 1 - 1
Server/Hotfix/Handler/G2C_TestHandler.cs

@@ -2,7 +2,7 @@
 
 namespace ETHotfix
 {
-    [MessageHandler(AppType.Benchmark)]
+    [MessageHandler]
     public class G2C_TestHandler: AMHandler<G2C_Test>
     {
         public static int count = 0;

+ 1 - 1
Server/Hotfix/Handler/M2A_ReloadHandler.cs

@@ -3,7 +3,7 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.AllServer)]
+	[MessageHandler]
 	public class M2A_ReloadHandler : AMRpcHandler<M2A_Reload, A2M_Reload>
 	{
 		protected override async ETTask Run(Session session, M2A_Reload request, A2M_Reload response, Action reply)

+ 17 - 22
Server/Hotfix/Module/Actor/ActorMessageDispatcherComponentSystem.cs

@@ -5,10 +5,11 @@ using ETModel;
 namespace ETHotfix
 {
 	[ObjectSystem]
-	public class ActorMessageDispatcherComponentStartSystem: AwakeSystem<ActorMessageDispatcherComponent>
+	public class ActorMessageDispatcherComponentAwakeSystem: AwakeSystem<ActorMessageDispatcherComponent>
 	{
 		public override void Awake(ActorMessageDispatcherComponent self)
 		{
+			ActorMessageDispatcherComponent.Instance = self;
 			self.Awake();
 		}
 	}
@@ -21,6 +22,16 @@ namespace ETHotfix
 			self.Load();
 		}
 	}
+	
+	[ObjectSystem]
+	public class ActorMessageDispatcherComponentDestroySystem: DestroySystem<ActorMessageDispatcherComponent>
+	{
+		public override void Destroy(ActorMessageDispatcherComponent self)
+		{
+			self.ActorMessageHandlers.Clear();
+			ActorMessageDispatcherComponent.Instance = null;
+		}
+	}
 
 	/// <summary>
 	/// Actor消息分发组件
@@ -34,27 +45,11 @@ namespace ETHotfix
 
 		public static void Load(this ActorMessageDispatcherComponent self)
 		{
-			AppType appType = StartConfigComponent.Instance.StartConfig.AppType;
-
 			self.ActorMessageHandlers.Clear();
 
-			List<Type> types = Game.EventSystem.GetTypes(typeof(ActorMessageHandlerAttribute));
-
-			types = Game.EventSystem.GetTypes(typeof (ActorMessageHandlerAttribute));
+			HashSet<Type> types = Game.EventSystem.GetTypes(typeof (ActorMessageHandlerAttribute));
 			foreach (Type type in types)
 			{
-				object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-				
-				ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute) attrs[0];
-				if (!messageHandlerAttribute.Type.Is(appType))
-				{
-					continue;
-				}
-
 				object obj = Activator.CreateInstance(type);
 
 				IMActorHandler imHandler = obj as IMActorHandler;
@@ -72,14 +67,14 @@ namespace ETHotfix
 		/// 分发actor消息
 		/// </summary>
 		public static async ETTask Handle(
-				this ActorMessageDispatcherComponent self, Entity entity, ActorMessageInfo actorMessageInfo)
+				this ActorMessageDispatcherComponent self, Entity entity, Session session, object message)
 		{
-			if (!self.ActorMessageHandlers.TryGetValue(actorMessageInfo.Message.GetType(), out IMActorHandler handler))
+			if (!self.ActorMessageHandlers.TryGetValue(message.GetType(), out IMActorHandler handler))
 			{
-				throw new Exception($"not found message handler: {MongoHelper.ToJson(actorMessageInfo.Message)}");
+				throw new Exception($"not found message handler: {message}");
 			}
 
-			await handler.Handle(actorMessageInfo.Session, entity, actorMessageInfo.Message);
+			await handler.Handle(session, entity, message);
 		}
 	}
 }

+ 128 - 0
Server/Hotfix/Module/Actor/ActorMessageSenderComponentSystem.cs

@@ -0,0 +1,128 @@
+using System;
+using ETModel;
+
+namespace ETHotfix
+{
+    [ObjectSystem]
+    public class ActorMessageSenderComponentAwakeSystem : AwakeSystem<ActorMessageSenderComponent>
+    {
+        public override void Awake(ActorMessageSenderComponent self)
+        {
+            ActorMessageSenderComponent.Instance = self;
+
+            self.TimeoutCheckTimer = TimerComponent.Instance.NewRepeatedTimer(10 * 1000, self.Check);
+        }
+    }
+    
+    [ObjectSystem]
+    public class ActorMessageSenderComponentDestroySystem: DestroySystem<ActorMessageSenderComponent>
+    {
+        public override void Destroy(ActorMessageSenderComponent self)
+        {
+            ActorMessageSenderComponent.Instance = null;
+            TimerComponent.Instance.Remove(self.TimeoutCheckTimer);
+            self.TimeoutCheckTimer = 0;
+            self.TimeoutActorMessageSenders.Clear();
+        }
+    }
+    
+    public static class ActorMessageSenderComponentSystem
+    {
+        public static void Check(this ActorMessageSenderComponent self)
+        {
+            long timeNow = TimeHelper.Now();
+            foreach ((int key, ActorMessageSender value) in self.requestCallback)
+            {
+                if (timeNow < value.CreateTime + ActorMessageSenderComponent.TIMEOUT_TIME)
+                {
+                    continue;
+                }
+                self.TimeoutActorMessageSenders.Add(key);
+            }
+
+            foreach (int rpcId in self.TimeoutActorMessageSenders)
+            {
+                ActorMessageSender actorMessageSender = self.requestCallback[rpcId];
+                self.requestCallback.Remove(rpcId);
+                Log.Error($"actor request timeout: {rpcId}");
+                actorMessageSender.Callback.Invoke(new ActorResponse() {Error = ErrorCode.ERR_ActorTimeout});
+            }
+            
+            self.TimeoutActorMessageSenders.Clear();
+        }
+        
+        public static void Send(this ActorMessageSenderComponent self, long actorId, IActorMessage message)
+        {
+            if (actorId == 0)
+            {
+                throw new Exception($"actor id is 0: {MongoHelper.ToJson(message)}");
+            }
+            string address = StartConfigComponent.Instance.GetProcessInnerAddress(IdGenerater.GetProcessId(actorId));
+            Session session = NetInnerComponent.Instance.Get(address);
+            message.ActorId = actorId;
+            session.Send(message);
+        }
+		
+        public static ETTask<IActorResponse> Call(this ActorMessageSenderComponent self, long actorId, IActorRequest message)
+        {
+            if (actorId == 0)
+            {
+                throw new Exception($"actor id is 0: {MongoHelper.ToJson(message)}");
+            }
+            
+            string address = StartConfigComponent.Instance.GetProcessInnerAddress(IdGenerater.GetProcessId(actorId));
+            Session session = NetInnerComponent.Instance.Get(address);
+            message.ActorId = actorId & IdGenerater.HeadMask | IdGenerater.Head;
+            message.RpcId = ++self.RpcId;
+			
+            var tcs = new ETTaskCompletionSource<IActorResponse>();
+            self.requestCallback.Add(message.RpcId, new ActorMessageSender((response) =>
+            {
+                if (ErrorCode.IsRpcNeedThrowException(response.Error))
+                {
+                    tcs.SetException(new Exception($"Rpc error: {MongoHelper.ToJson(response)}"));
+                    return;
+                }
+
+                
+                tcs.SetResult(response);
+            }));
+            session.Send(message);
+            return tcs.Task;
+        }
+		
+        public static ETTask<IActorResponse> CallWithoutException(this ActorMessageSenderComponent self, long actorId,  IActorRequest message)
+        {
+            if (actorId == 0)
+            {
+                throw new Exception($"actor id is 0: {MongoHelper.ToJson(message)}");
+            }
+            
+            string address = StartConfigComponent.Instance.GetProcessInnerAddress(IdGenerater.GetProcessId(actorId));
+            Session session = NetInnerComponent.Instance.Get(address);
+            message.ActorId = actorId & IdGenerater.HeadMask | IdGenerater.Head;
+            message.RpcId = ++self.RpcId;
+			
+            var tcs = new ETTaskCompletionSource<IActorResponse>();
+            self.requestCallback.Add(message.RpcId, new ActorMessageSender((response) =>
+            {
+                tcs.SetResult(response);
+            }));
+            session.Send(message);
+            return tcs.Task;
+        }
+		
+        public static void RunMessage(this ActorMessageSenderComponent self, IActorResponse response)
+        {
+            ActorMessageSender actorMessageSender;
+            if (!self.requestCallback.TryGetValue(response.RpcId, out actorMessageSender))
+            {
+                Log.Error($"not found rpc, maybe request timeout, response message: {StringHelper.MessageToStr(response)}");
+                return;
+            }
+            self.requestCallback.Remove(response.RpcId);
+            
+            actorMessageSender.Callback(response);
+        }
+    }
+}

+ 0 - 28
Server/Hotfix/Module/Actor/ActorMessageSenderHelper.cs

@@ -1,28 +0,0 @@
-using ETModel;
-
-namespace ETHotfix
-{
-	public static class ActorMessageSenderHelper
-	{
-		public static void Send(this ActorMessageSender self, IActorMessage message)
-		{   
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.Address);
-			message.ActorId = self.ActorId;
-			session.Send(message);
-		}
-		
-		public static async ETTask<IActorResponse> Call(this ActorMessageSender self, IActorRequest message)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.Address);
-			message.ActorId = self.ActorId;
-			return (IActorResponse)await session.Call(message);
-		}
-		
-		public static async ETTask<IActorResponse> CallWithoutException(this ActorMessageSender self, IActorRequest message)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.Address);
-			message.ActorId = self.ActorId;
-			return (IActorResponse)await session.CallWithoutException(message);
-		}
-	}
-}

+ 2 - 24
Server/Hotfix/Module/Actor/MailBoxComponentSystem.cs

@@ -13,33 +13,11 @@ namespace ETHotfix
 	}
 
 	[ObjectSystem]
-	public class MailBoxComponentAwake1System : AwakeSystem<MailBoxComponent, string>
+	public class MailBoxComponentAwake1System : AwakeSystem<MailBoxComponent, MailboxType>
 	{
-		public override void Awake(MailBoxComponent self, string mailboxType)
+		public override void Awake(MailBoxComponent self, MailboxType mailboxType)
 		{
 			self.MailboxType = mailboxType;
 		}
 	}
-
-	/// <summary>
-	/// 挂上这个组件表示该Entity是一个Actor, 接收的消息将会队列处理
-	/// </summary>
-	public static class MailBoxComponentHelper
-	{
-		public static async ETTask AddLocation(this MailBoxComponent self)
-		{
-			await Game.Scene.GetComponent<LocationProxyComponent>().Add(self.Entity.Id, self.Entity.InstanceId);
-		}
-
-		public static async ETTask RemoveLocation(this MailBoxComponent self)
-		{
-			await Game.Scene.GetComponent<LocationProxyComponent>().Remove(self.Entity.Id);
-		}
-
-		public static async ETTask Add(this MailBoxComponent self, Session session, object message)
-		{
-			MailboxDispatcherComponent mailboxDispatcherComponent = Game.Scene.GetComponent<MailboxDispatcherComponent>();
-			await mailboxDispatcherComponent.Handle(self, session, message);
-		}
-	}
 }

+ 16 - 15
Server/Hotfix/Module/Actor/MailboxDispatcherComponentSystem.cs

@@ -21,22 +21,29 @@ namespace ETHotfix
 			self.Load();
 		}
 	}
+	
+	[ObjectSystem]
+	public class MailboxDispatcherComponentDestroySystem: DestroySystem<MailboxDispatcherComponent>
+	{
+		public override void Destroy(MailboxDispatcherComponent self)
+		{
+			self.MailboxHandlers.Clear();
+		}
+	}
 
 	public static class MailboxDispatcherComponentHelper
 	{
 		public static void Awake(this MailboxDispatcherComponent self)
 		{
+			MailboxDispatcherComponent.Instance = self;
 			self.Load();
 		}
 
 		public static void Load(this MailboxDispatcherComponent self)
 		{
-			AppType appType = StartConfigComponent.Instance.StartConfig.AppType;
-
 			self.MailboxHandlers.Clear();
 
-			List<Type> types = Game.EventSystem.GetTypes(typeof(MailboxHandlerAttribute));
-
+			HashSet<Type> types = Game.EventSystem.GetTypes(typeof(MailboxHandlerAttribute));
 			foreach (Type type in types)
 			{
 				object[] attrs = type.GetCustomAttributes(typeof(MailboxHandlerAttribute), false);
@@ -46,20 +53,15 @@ namespace ETHotfix
 				}
 
 				MailboxHandlerAttribute mailboxHandlerAttribute = (MailboxHandlerAttribute) attrs[0];
-				if (!mailboxHandlerAttribute.Type.Is(appType))
-				{
-					continue;
-				}
 
 				object obj = Activator.CreateInstance(type);
 
-				IMailboxHandler iMailboxHandler = obj as IMailboxHandler;
-				if (iMailboxHandler == null)
+				if (!(obj is IMailboxHandler iMailboxHandler))
 				{
 					throw new Exception($"actor handler not inherit IEntityActorHandler: {obj.GetType().FullName}");
 				}
 
-				self.MailboxHandlers.Add(mailboxHandlerAttribute.MailboxType, iMailboxHandler);
+				self.MailboxHandlers.Add((int)mailboxHandlerAttribute.MailboxType, iMailboxHandler);
 			}
 		}
 
@@ -67,12 +69,11 @@ namespace ETHotfix
 		/// 根据mailbox类型做不同的处理
 		/// </summary>
 		public static async ETTask Handle(
-				this MailboxDispatcherComponent self, MailBoxComponent mailBoxComponent, Session session, object message)
+				this MailboxDispatcherComponent self, Entity entity, MailboxType mailboxType, Session session, object message)
 		{
-			IMailboxHandler iMailboxHandler;
-			if (self.MailboxHandlers.TryGetValue(mailBoxComponent.MailboxType, out iMailboxHandler))
+			if (self.MailboxHandlers.TryGetValue((int) mailboxType, out IMailboxHandler iMailboxHandler))
 			{
-				await iMailboxHandler.Handle(session, mailBoxComponent.Entity, message);
+				await iMailboxHandler.Handle(session, entity, message);
 			}
 		}
 	}

+ 1 - 1
Server/Hotfix/Module/Actor/MailboxGateSessionHandler.cs

@@ -6,7 +6,7 @@ namespace ETHotfix
 	/// <summary>
 	/// gate session类型的Mailbox,收到的actor消息直接转发给客户端
 	/// </summary>
-	[MailboxHandler(AppType.Gate, MailboxType.GateSession)]
+	[MailboxHandler(MailboxType.GateSession)]
 	public class MailboxGateSessionHandler : IMailboxHandler
 	{
 		public async ETTask Handle(Session session, Entity entity, object actorMessage)

+ 2 - 3
Server/Hotfix/Module/Actor/MailboxMessageDispatcherHandler.cs

@@ -6,15 +6,14 @@ namespace ETHotfix
 	/// <summary>
 	/// 消息分发类型的Mailbox,对mailbox中的消息进行分发处理
 	/// </summary>
-	[MailboxHandler(AppType.AllServer, MailboxType.MessageDispatcher)]
+	[MailboxHandler(MailboxType.MessageDispatcher)]
 	public class MailboxMessageDispatcherHandler : IMailboxHandler
 	{
 		public async ETTask Handle(Session session, Entity entity, object actorMessage)
 		{
 			try
 			{
-				await Game.Scene.GetComponent<ActorMessageDispatcherComponent>().Handle(
-					entity, new ActorMessageInfo() { Session = session, Message = actorMessage });
+				await ActorMessageDispatcherComponent.Instance.Handle(entity, session, actorMessage);
 			}
 			catch (Exception e)
 			{

+ 67 - 31
Server/Hotfix/Module/ActorLocation/ActorLocationSenderComponentSystem.cs

@@ -1,55 +1,91 @@
-using System.Collections.Generic;
+using System;
 using ETModel;
 
 namespace ETHotfix
 {
     [ObjectSystem]
-    public class ActorLocationSenderComponentSystem : StartSystem<ActorLocationSenderComponent>
+    public class ActorLocationSenderComponentAwakeSystem : AwakeSystem<ActorLocationSenderComponent>
     {
-        public override void Start(ActorLocationSenderComponent self)
+        public override void Awake(ActorLocationSenderComponent self)
         {
-            StartAsync(self).Coroutine();
+            ActorLocationSenderComponent.Instance = self;
+            
+            // 每10s扫描一次过期的actorproxy进行回收,过期时间是1分钟
+            // 可能由于bug或者进程挂掉,导致ActorLocationSender发送的消息没有确认,结果无法自动删除,每一分钟清理一次这种ActorLocationSender
+            self.CheckTimer = TimerComponent.Instance.NewRepeatedTimer(10 * 1000, self.Check);
         }
-        
-        // 每10s扫描一次过期的actorproxy进行回收,过期时间是1分钟
-        // 可能由于bug或者进程挂掉,导致ActorLocationSender发送的消息没有确认,结果无法自动删除,每一分钟清理一次这种ActorLocationSender
-        public async ETVoid StartAsync(ActorLocationSenderComponent self)
+    }
+    
+    [ObjectSystem]
+    public class ActorLocationSenderComponentDestroySystem: DestroySystem<ActorLocationSenderComponent>
+    {
+        public override void Destroy(ActorLocationSenderComponent self)
         {
-            List<long> timeoutActorProxyIds = new List<long>();
-
-            while (true)
+            ActorLocationSenderComponent.Instance = null;
+            TimerComponent.Instance.Remove(self.CheckTimer);
+            self.CheckTimer = 0;
+        }
+    }
+    
+    public static class ActorLocationSenderComponentSystem
+    {
+        public static void Check(this ActorLocationSenderComponent self)
+        {
+            using (ListComponent<long> list = EntityFactory.Create<ListComponent<long>>(self.Domain))
             {
-                await Game.Scene.GetComponent<TimerComponent>().WaitAsync(10000);
-
-                if (self.IsDisposed)
-                {
-                    return;
-                }
-
-                timeoutActorProxyIds.Clear();
-
                 long timeNow = TimeHelper.Now();
-                foreach (long id in self.ActorLocationSenders.Keys)
+                foreach ((long key, Entity value) in self.Children)
                 {
-                    ActorLocationSender actorLocationMessageSender = self.ActorLocationSenders[id];
-                    if (actorLocationMessageSender == null)
-                    {
-                        continue;
-                    }
+                    ActorLocationSender actorLocationMessageSender = (ActorLocationSender) value;
 
-                    if (timeNow < actorLocationMessageSender.LastRecvTime + 60 * 1000)
+                    if (timeNow > actorLocationMessageSender.LastSendOrRecvTime + ActorLocationSenderComponent.TIMEOUT_TIME)
                     {
-                        continue;
+                        list.List.Add(key);
                     }
-
-                    timeoutActorProxyIds.Add(id);
                 }
 
-                foreach (long id in timeoutActorProxyIds)
+                foreach (long id in list.List)
                 {
                     self.Remove(id);
                 }
             }
         }
+        
+        private static ActorLocationSender Get(this ActorLocationSenderComponent self, long id)
+        {
+            if (id == 0)
+            {
+                throw new Exception($"actor id is 0");
+            }
+            if (self.Children.TryGetValue(id, out Entity actorLocationSender))
+            {
+                return (ActorLocationSender)actorLocationSender;
+            }
+			
+            actorLocationSender = EntityFactory.CreateWithId<ActorLocationSender>(self.Domain, id);
+            actorLocationSender.Parent = self;
+            return (ActorLocationSender)actorLocationSender;
+        }
+		
+        private static void Remove(this ActorLocationSenderComponent self, long id)
+        {
+            if (!self.Children.TryGetValue(id, out Entity actorMessageSender))
+            {
+                return;
+            }
+            actorMessageSender.Dispose();
+        }
+        
+        public static void Send(this ActorLocationSenderComponent self, long entityId, IActorLocationMessage message)
+        {
+            ActorLocationSender actorLocationSender = self.Get(entityId);
+            actorLocationSender.Send(message);
+        }
+		
+        public static async ETTask<IActorResponse> Call(this ActorLocationSenderComponent self, long entityId, IActorLocationRequest message)
+        {
+            ActorLocationSender actorLocationSender = self.Get(entityId);
+            return await actorLocationSender.Call(message);
+        }
     }
 }

+ 103 - 98
Server/Hotfix/Module/ActorLocation/ActorLocationSenderSystem.cs

@@ -4,123 +4,128 @@ using ETModel;
 namespace ETHotfix
 {
     [ObjectSystem]
-    public class ActorLocationSenderAwakeSystem : AwakeSystem<ActorLocationSender>
+    public class ActorLocationSenderAwakeSystem: AwakeSystem<ActorLocationSender>
     {
         public override void Awake(ActorLocationSender self)
         {
-            self.LastRecvTime = TimeHelper.Now();
+            self.LastSendOrRecvTime = TimeHelper.Now();
             self.FailTimes = 0;
             self.ActorId = 0;
-            
+
             StartAsync(self).Coroutine();
         }
-        
+
         public async ETVoid StartAsync(ActorLocationSender self)
         {
-	        using (await CoroutineLockComponent.Instance.Wait(self.Id))
-	        {
-		        self.ActorId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(self.Id);
-	        }
+            using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ActorLocationSender, self.Id))
+            {
+                self.ActorId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(self.Id);
+            }
         }
     }
-	
+
     [ObjectSystem]
-    public class ActorLocationSenderDestroySystem : DestroySystem<ActorLocationSender>
+    public class ActorLocationSenderDestroySystem: DestroySystem<ActorLocationSender>
     {
         public override void Destroy(ActorLocationSender self)
         {
-            self.Id = 0;
-            self.LastRecvTime = 0;
+            Log.Debug($"actor location remove: {self.Id}");
+            self.LastSendOrRecvTime = 0;
             self.ActorId = 0;
             self.FailTimes = 0;
         }
     }
-    
-    public static class ActorLocationSenderSystem
+
+    public static class ActorLocationSenderHelper
     {
-		private static async ETTask<IActorResponse> Run(this ActorLocationSender self, IActorRequest iActorRequest)
-		{
-			long instanceId = self.InstanceId;
-			using (await CoroutineLockComponent.Instance.Wait(self.Id))
-			{
-				if (self.InstanceId != instanceId)
-				{
-					throw new RpcException(ErrorCode.ERR_ActorRemove, "");
-				}
-				
-				ActorMessageSender actorMessageSender = Game.Scene.GetComponent<ActorMessageSenderComponent>().Get(self.ActorId);
-				try
-				{
-					// ERR_NotFoundActor是需要抛异常的,但是这里不能抛
-					IActorResponse response = await actorMessageSender.CallWithoutException(iActorRequest);
-					
-					switch (response.Error)
-					{
-						case ErrorCode.ERR_NotFoundActor:
-							// 如果没找到Actor,重试
-							++self.FailTimes;
-
-							// 失败MaxFailTimes次则清空actor发送队列,返回失败
-							if (self.FailTimes > ActorLocationSender.MaxFailTimes)
-							{
-								// 失败直接删除actorproxy
-								Log.Info($"actor send message fail, actorid: {self.Id}");
-								self.GetParent<ActorLocationSenderComponent>().Remove(self.Id);
-								throw new RpcException(response.Error, "");
-							}
-
-							// 等待0.5s再发送
-							await Game.Scene.GetComponent<TimerComponent>().WaitAsync(500);
-							if (self.InstanceId != instanceId)
-							{
-								throw new RpcException(ErrorCode.ERR_ActorRemove, "");
-							}
-							self.ActorId = await Game.Scene.GetComponent<LocationProxyComponent>().Get(self.Id);
-							IActorResponse iActorResponse = await Run(self, iActorRequest);
-							if (self.InstanceId != instanceId)
-							{
-								throw new RpcException(ErrorCode.ERR_ActorRemove, "");
-							}
-							return iActorResponse;
-
-						case ErrorCode.ERR_ActorNoMailBoxComponent:
-							self.GetParent<ActorLocationSenderComponent>().Remove(self.Id);
-							throw new RpcException(response.Error, "");
-
-						default:
-							self.LastRecvTime = TimeHelper.Now();
-							self.FailTimes = 0;
-							break;
-					}
-					
-					return response;
-				}
-				catch (Exception)
-				{
-					self.GetParent<ActorLocationSenderComponent>().Remove(self.Id);
-					throw;
-				}
-			}
-		}
-
-	    public static async ETVoid Send(this ActorLocationSender self, IActorLocationMessage request)
-	    {
-		    if (request == null)
-		    {
-			    throw new Exception($"actor location send message is null");
-		    }
-		    
-			await Run(self, request);
-	    }
-
-		public static async ETTask<IActorLocationResponse> Call(this ActorLocationSender self, IActorLocationRequest request)
-		{
-			if (request == null)
-			{
-				throw new Exception($"actor location call message is null");
-			}
-			
-			return await Run(self, request) as IActorLocationResponse;
-		}
+        private static async ETTask<IActorResponse> Run(this ActorLocationSender self, IActorRequest iActorRequest)
+        {
+            long instanceId = self.InstanceId;
+            using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ActorLocationSender, self.Id))
+            {
+                if (self.InstanceId != instanceId)
+                {
+                    throw new RpcException(ErrorCode.ERR_ActorRemove, $"{MongoHelper.ToJson(iActorRequest)}");
+                }
+
+                return await self.RunInner(iActorRequest);
+            }
+        }
+
+        private static async ETTask<IActorResponse> RunInner(this ActorLocationSender self, IActorRequest iActorRequest)
+        {
+            try
+            {
+                if (self.ActorId == 0)
+                {
+                    Log.Info($"actor send message fail, actorid: {self.Id}");
+                    self.Dispose();
+                    return new ActorResponse() { Error = ErrorCode.ERR_ActorNotOnline };
+                }
+
+                self.LastSendOrRecvTime = TimeHelper.Now();
+                IActorResponse response = await ActorMessageSenderComponent.Instance.CallWithoutException(self.ActorId, iActorRequest);
+
+                switch (response.Error)
+                {
+                    case ErrorCode.ERR_NotFoundActor:
+                    {
+                        // 如果没找到Actor,重试
+                        ++self.FailTimes;
+                        if (self.FailTimes > ActorLocationSender.MaxFailTimes)
+                        {
+                            Log.Info($"actor send message fail, actorid: {self.Id}");
+                            self.Dispose();
+                            return response;
+                        }
+
+                        // 等待0.5s再发送
+                        long instanceId = self.InstanceId;
+                        await TimerComponent.Instance.WaitAsync(500);
+                        if (self.InstanceId != instanceId)
+                        {
+                            throw new RpcException(ErrorCode.ERR_ActorRemove, $"{MongoHelper.ToJson(iActorRequest)}");
+                        }
+                        self.ActorId = await LocationProxyComponent.Instance.Get(self.Id);
+                        return await self.RunInner(iActorRequest);
+                    }
+                }
+
+                self.LastSendOrRecvTime = TimeHelper.Now();
+                self.FailTimes = 0;
+
+                return response;
+            }
+            catch (RpcException)
+            {
+                self.Dispose();
+                throw;
+            }
+            catch (Exception e)
+            {
+                self.Dispose();
+                throw new Exception($"{MongoHelper.ToJson(iActorRequest)}\n{e}");
+            }
+        }
+
+        public static void Send(this ActorLocationSender self, IActorLocationMessage request)
+        {
+            if (request == null)
+            {
+                throw new Exception($"actor location send message is null");
+            }
+
+            self.Run(request).Coroutine();
+        }
+
+        public static async ETTask<IActorResponse> Call(this ActorLocationSender self, IActorLocationRequest request)
+        {
+            if (request == null)
+            {
+                throw new Exception($"actor location call message is null");
+            }
+
+            return await self.Run(request);
+        }
     }
 }

+ 34 - 16
Server/Hotfix/Module/ActorLocation/LocationProxyComponentSystem.cs

@@ -1,4 +1,5 @@
-using ETModel;
+using System;
+using ETModel;
 
 namespace ETHotfix
 {
@@ -10,46 +11,63 @@ namespace ETHotfix
 			self.Awake();
 		}
 	}
-
+	
 	public static class LocationProxyComponentEx
 	{
 		public static void Awake(this LocationProxyComponent self)
 		{
-			StartConfigComponent startConfigComponent = StartConfigComponent.Instance;
-
-			StartConfig startConfig = startConfigComponent.LocationConfig;
-			self.LocationAddress = startConfig.GetComponent<InnerConfig>().IPEndPoint;
+			LocationProxyComponent.Instance = self;
 		}
 
 		public static async ETTask Add(this LocationProxyComponent self, long key, long instanceId)
 		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.LocationAddress);
-			await session.Call(new ObjectAddRequest() { Key = key, InstanceId = instanceId });
+			await MessageHelper.CallActor(
+				StartConfigComponent.Instance.GetInstanceId(SceneType.Location), 
+				new ObjectAddRequest() { Key = key, InstanceId = instanceId });
 		}
 
 		public static async ETTask Lock(this LocationProxyComponent self, long key, long instanceId, int time = 1000)
 		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.LocationAddress);
-			await session.Call(new ObjectLockRequest() { Key = key, InstanceId = instanceId, Time = time });
+			await MessageHelper.CallActor(
+				StartConfigComponent.Instance.GetInstanceId(SceneType.Location), 
+				new ObjectLockRequest() { Key = key, InstanceId = instanceId, Time = time });
 		}
 
 		public static async ETTask UnLock(this LocationProxyComponent self, long key, long oldInstanceId, long instanceId)
 		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.LocationAddress);
-			await session.Call(new ObjectUnLockRequest() { Key = key, OldInstanceId = oldInstanceId, InstanceId = instanceId});
+			await MessageHelper.CallActor(
+				StartConfigComponent.Instance.GetInstanceId(SceneType.Location),
+				new ObjectUnLockRequest() { Key = key, OldInstanceId = oldInstanceId, InstanceId = instanceId });
 		}
 
 		public static async ETTask Remove(this LocationProxyComponent self, long key)
 		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.LocationAddress);
-			await session.Call(new ObjectRemoveRequest() { Key = key });
+			await MessageHelper.CallActor(
+				StartConfigComponent.Instance.GetInstanceId(SceneType.Location),
+				new ObjectRemoveRequest() { Key = key });
 		}
 
 		public static async ETTask<long> Get(this LocationProxyComponent self, long key)
 		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.LocationAddress);
-			ObjectGetResponse response = (ObjectGetResponse)await session.Call(new ObjectGetRequest() { Key = key });
+			if (key == 0)
+			{
+				throw new Exception($"get location key 0");
+			}
+			ObjectGetResponse response =
+					(ObjectGetResponse)await MessageHelper.CallActor(
+						StartConfigComponent.Instance.GetInstanceId(SceneType.Location), 
+						new ObjectGetRequest() { Key = key });
 			return response.InstanceId;
 		}
+		
+		public static async ETTask AddLocation(this Entity self)
+		{
+			await Game.Scene.GetComponent<LocationProxyComponent>().Add(self.Id, self.InstanceId);
+		}
+
+		public static async ETTask RemoveLocation(this Entity self)
+		{
+			await Game.Scene.GetComponent<LocationProxyComponent>().Remove(self.Id);
+		}
 	}
 }

+ 4 - 4
Server/Hotfix/Module/ActorLocation/ObjectAddRequestHandler.cs

@@ -3,12 +3,12 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Location)]
-	public class ObjectAddRequestHandler : AMRpcHandler<ObjectAddRequest, ObjectAddResponse>
+	[MessageHandler]
+	public class ObjectAddRequestHandler : AMActorRpcHandler<Scene, ObjectAddRequest, ObjectAddResponse>
 	{
-		protected override async ETTask Run(Session session, ObjectAddRequest request, ObjectAddResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, ObjectAddRequest request, ObjectAddResponse response, Action reply)
 		{
-			await Game.Scene.GetComponent<LocationComponent>().Add(request.Key, request.InstanceId);
+			await scene.GetComponent<LocationComponent>().Add(request.Key, request.InstanceId);
 			reply();
 		}
 	}

+ 4 - 4
Server/Hotfix/Module/ActorLocation/ObjectGetRequestHandler.cs

@@ -3,12 +3,12 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Location)]
-	public class ObjectGetRequestHandler : AMRpcHandler<ObjectGetRequest, ObjectGetResponse>
+	[MessageHandler]
+	public class ObjectGetRequestHandler : AMActorRpcHandler<Scene, ObjectGetRequest, ObjectGetResponse>
 	{
-		protected override async ETTask Run(Session session, ObjectGetRequest request, ObjectGetResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, ObjectGetRequest request, ObjectGetResponse response, Action reply)
 		{
-			long instanceId = await Game.Scene.GetComponent<LocationComponent>().Get(request.Key);
+			long instanceId = await scene.GetComponent<LocationComponent>().Get(request.Key);
 			if (instanceId == 0)
 			{
 				response.Error = ErrorCode.ERR_ActorLocationNotFound;

+ 4 - 4
Server/Hotfix/Module/ActorLocation/ObjectLockRequestHandler.cs

@@ -3,12 +3,12 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Location)]
-	public class ObjectLockRequestHandler : AMRpcHandler<ObjectLockRequest, ObjectLockResponse>
+	[MessageHandler]
+	public class ObjectLockRequestHandler : AMActorRpcHandler<Scene, ObjectLockRequest, ObjectLockResponse>
 	{
-		protected override async ETTask Run(Session session, ObjectLockRequest request, ObjectLockResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, ObjectLockRequest request, ObjectLockResponse response, Action reply)
 		{
-			Game.Scene.GetComponent<LocationComponent>().Lock(request.Key, request.InstanceId, request.Time).Coroutine();
+			scene.GetComponent<LocationComponent>().Lock(request.Key, request.InstanceId, request.Time).Coroutine();
 			reply();
 		}
 	}

+ 4 - 4
Server/Hotfix/Module/ActorLocation/ObjectRemoveRequestHandler.cs

@@ -3,12 +3,12 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Location)]
-	public class ObjectRemoveRequestHandler : AMRpcHandler<ObjectRemoveRequest, ObjectRemoveResponse>
+	[MessageHandler]
+	public class ObjectRemoveRequestHandler : AMActorRpcHandler<Scene, ObjectRemoveRequest, ObjectRemoveResponse>
 	{
-		protected override async ETTask Run(Session session, ObjectRemoveRequest request, ObjectRemoveResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, ObjectRemoveRequest request, ObjectRemoveResponse response, Action reply)
 		{
-			await Game.Scene.GetComponent<LocationComponent>().Remove(request.Key);
+			await scene.GetComponent<LocationComponent>().Remove(request.Key);
 			reply();
 			await ETTask.CompletedTask;
 		}

+ 4 - 4
Server/Hotfix/Module/ActorLocation/ObjectUnLockRequestHandler.cs

@@ -3,12 +3,12 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Location)]
-	public class ObjectUnLockRequestHandler : AMRpcHandler<ObjectUnLockRequest, ObjectUnLockResponse>
+	[MessageHandler]
+	public class ObjectUnLockRequestHandler : AMActorRpcHandler<Scene, ObjectUnLockRequest, ObjectUnLockResponse>
 	{
-		protected override async ETTask Run(Session session, ObjectUnLockRequest request, ObjectUnLockResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, ObjectUnLockRequest request, ObjectUnLockResponse response, Action reply)
 		{
-			Game.Scene.GetComponent<LocationComponent>().UnLock(request.Key, request.OldInstanceId, request.InstanceId);
+			scene.GetComponent<LocationComponent>().UnLock(request.Key, request.OldInstanceId, request.InstanceId);
 			reply();
 			await ETTask.CompletedTask;
 		}

+ 1 - 16
Server/Hotfix/Module/Config/ConfigComponentSystem.cs

@@ -31,26 +31,11 @@ namespace ETHotfix
 
 		public static void Load(this ConfigComponent self)
 		{
-			AppType appType = StartConfigComponent.Instance.StartConfig.AppType;
-			
 			self.AllConfig.Clear();
-			List<Type> types = Game.EventSystem.GetTypes(typeof(ConfigAttribute));
+			HashSet<Type> types = Game.EventSystem.GetTypes(typeof(ConfigAttribute));
 
 			foreach (Type type in types)
 			{
-				object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-				
-				ConfigAttribute configAttribute = attrs[0] as ConfigAttribute;
-				// 只加载指定的配置
-				if (!configAttribute.Type.Is(appType))
-				{
-					continue;
-				}
-				
 				object obj = Activator.CreateInstance(type);
 
 				ACategory iCategory = obj as ACategory;

+ 270 - 0
Server/Hotfix/Module/DB/DBComponentSystem.cs

@@ -0,0 +1,270 @@
+using System;
+using System.Collections.Generic;
+using System.Linq.Expressions;
+using MongoDB.Driver;
+
+namespace ETModel
+{
+	[ObjectSystem]
+	public class DBComponentAwakeSystem : AwakeSystem<DBComponent, DBConfig>
+	{
+		public override void Awake(DBComponent self, DBConfig dbConfig)
+		{
+			
+			string connectionString = dbConfig.ConnectionString;
+			self.mongoClient = new MongoClient(connectionString);
+			self.database = self.mongoClient.GetDatabase(dbConfig.DBName);
+			
+			self.Transfers.Clear();
+			foreach (Type type in Game.EventSystem.GetTypes())
+			{
+				if (type == typeof (IDBCollection))
+				{
+					continue;
+				}
+				if (!typeof(IDBCollection).IsAssignableFrom(type))
+				{
+					continue;
+				}
+				self.Transfers.Add(type.Name);
+			}
+			
+			DBComponent.Instance = self;
+		}
+	}
+	
+	[ObjectSystem]
+    public class DBComponentDestroySystem: DestroySystem<DBComponent>
+    {
+        public override void Destroy(DBComponent self)
+        {
+	        DBComponent.Instance = null;
+	        self.Transfers.Clear();
+        }
+    }
+	
+    public static class DBComponentSystem
+    {
+	    #region Query
+
+	    public static async ETTask<T> Query<T>(this DBComponent self, long id, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, id % DBComponent.TaskCount))
+		    {
+			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(d => d.Id == id);
+
+			    return await cursor.FirstOrDefaultAsync();
+		    }
+	    }
+	    
+	    public static async ETTask<List<T>> Query<T>(this DBComponent self, Expression<Func<T, bool>> filter, string collection = null)
+			    where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    {
+			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filter);
+
+			    return await cursor.ToListAsync();
+		    }
+	    }
+
+	    public static async ETTask<List<T>> Query<T>(this DBComponent self, long taskId, Expression<Func<T, bool>> filter, string collection = null)
+			    where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, taskId % DBComponent.TaskCount))
+		    {
+			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filter);
+
+			    return await cursor.ToListAsync();
+		    }
+	    }
+	    
+	    public static async ETTask Query(this DBComponent self, long id, List<string> collectionNames, List<Entity> result)
+	    {
+		    if (collectionNames == null || collectionNames.Count == 0)
+		    {
+			    return;
+		    }
+
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, id % DBComponent.TaskCount))
+		    {
+			    foreach (string collectionName in collectionNames)
+			    {
+				    IAsyncCursor<Entity> cursor = await self.GetCollection(collectionName).FindAsync(d => d.Id == id);
+
+				    Entity e = await cursor.FirstOrDefaultAsync();
+
+				    if (e == null)
+				    {
+					    continue;
+				    }
+
+				    result.Add(e);
+			    }
+		    }
+	    }
+
+	    public static async ETTask<List<T>> QueryJson<T>(this DBComponent self, string json, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    {
+			    FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
+			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filterDefinition);
+			    return await cursor.ToListAsync();
+		    }
+	    }
+
+	    public static async ETTask<List<T>> QueryJson<T>(this DBComponent self, long taskId, string json, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    {
+			    FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
+			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filterDefinition);
+			    return await cursor.ToListAsync();
+		    }
+	    }
+
+	    #endregion
+
+	    #region Insert
+
+	    public static async ETTask InsertBatch<T>(this DBComponent self, IEnumerable<T> list, string collection = null) where T: Entity
+	    {
+		    if (collection == null)
+		    {
+			    collection = typeof (T).Name;
+		    }
+		    
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    {
+			    await self.GetCollection(collection).InsertManyAsync(list);
+		    }
+	    }
+
+	    #endregion
+
+	    #region Save
+
+	    public static async ETTask Save<T>(this DBComponent self, T entity, string collection = null) where T : Entity
+	    {
+		    if (entity == null)
+		    {
+			    Log.Error($"save entity is null: {typeof (T).Name}");
+
+			    return;
+		    }
+		    
+		    if (collection == null)
+		    {
+			    collection = entity.GetType().Name;
+		    }
+
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, entity.Id % DBComponent.TaskCount))
+		    {
+			    await self.GetCollection(collection).ReplaceOneAsync(d => d.Id == entity.Id, entity, new UpdateOptions { IsUpsert = true });
+		    }
+	    }
+
+	    public static async ETTask Save<T>(this DBComponent self, long taskId, T entity, string collection = null) where T : Entity
+	    {
+		    if (entity == null)
+		    {
+			    Log.Error($"save entity is null: {typeof (T).Name}");
+
+			    return;
+		    }
+
+		    if (collection == null)
+		    {
+			    collection = entity.GetType().Name;
+		    }
+
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, taskId % DBComponent.TaskCount))
+		    {
+			    await self.GetCollection(collection).ReplaceOneAsync(d => d.Id == entity.Id, entity, new UpdateOptions { IsUpsert = true });
+		    }
+	    }
+
+	    public static async ETTask Save(this DBComponent self, long id, List<Entity> entities)
+	    {
+		    if (entities == null)
+		    {
+			    Log.Error($"save entity is null");
+			    return;
+		    }
+
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, id % DBComponent.TaskCount))
+		    {
+			    foreach (Entity entity in entities)
+			    {
+				    if (entity == null)
+				    {
+					    continue;
+				    }
+
+				    await self.GetCollection(entity.GetType().Name)
+						    .ReplaceOneAsync(d => d.Id == entity.Id, entity, new UpdateOptions { IsUpsert = true });
+			    }
+		    }
+	    }
+
+	    public static async ETVoid SaveNotWait<T>(this DBComponent self, T entity, long taskId = 0, string collection = null) where T : Entity
+	    {
+		    if (taskId == 0)
+		    {
+			    await self.Save(entity, collection);
+
+			    return;
+		    }
+
+		    await self.Save(taskId, entity, collection);
+	    }
+
+	    #endregion
+
+	    #region Remove
+	    
+	    public static async ETTask<long> Remove<T>(this DBComponent self, long id, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, id % DBComponent.TaskCount))
+		    {
+			    DeleteResult result = await self.GetCollection<T>(collection).DeleteOneAsync(d => d.Id == id);
+
+			    return result.DeletedCount;
+		    }
+	    }
+
+	    public static async ETTask<long> Remove<T>(this DBComponent self, long taskId, long id, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, taskId % DBComponent.TaskCount))
+		    {
+			    DeleteResult result = await self.GetCollection<T>(collection).DeleteOneAsync(d => d.Id == id);
+
+			    return result.DeletedCount;
+		    }
+	    }
+
+	    public static async ETTask<long> Remove<T>(this DBComponent self, Expression<Func<T, bool>> filter, string collection = null) where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    {
+			    DeleteResult result = await self.GetCollection<T>(collection).DeleteManyAsync(filter);
+
+			    return result.DeletedCount;
+		    }
+	    }
+
+	    public static async ETTask<long> Remove<T>(this DBComponent self, long taskId, Expression<Func<T, bool>> filter, string collection = null)
+			    where T : Entity
+	    {
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, taskId % DBComponent.TaskCount))
+		    {
+			    DeleteResult result = await self.GetCollection<T>(collection).DeleteManyAsync(filter);
+
+			    return result.DeletedCount;
+		    }
+	    }
+
+	    #endregion
+    }
+}

+ 0 - 172
Server/Hotfix/Module/DB/DBProxyComponentSystem.cs

@@ -1,172 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-using System.Threading;
-using ETModel;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization;
-using MongoDB.Driver;
-
-namespace ETHotfix
-{
-	[ObjectSystem]
-	public class DbProxyComponentSystem : AwakeSystem<DBProxyComponent>
-	{
-		public override void Awake(DBProxyComponent self)
-		{
-			self.Awake();
-		}
-	}
-	
-	/// <summary>
-	/// 用来与数据库操作代理
-	/// </summary>
-	public static class DBProxyComponentEx
-	{
-		public static void Awake(this DBProxyComponent self)
-		{
-			StartConfig dbStartConfig = StartConfigComponent.Instance.DBConfig;
-			self.dbAddress = dbStartConfig.GetComponent<InnerConfig>().IPEndPoint;
-		}
-
-		public static async ETTask Save(this DBProxyComponent self, ComponentWithId component)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-			await session.Call(new DBSaveRequest { Component = component });
-		}
-
-		public static async ETTask SaveBatch(this DBProxyComponent self, List<ComponentWithId> components)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-			await session.Call(new DBSaveBatchRequest { Components = components });
-		}
-
-		public static async ETTask Save(this DBProxyComponent self, ComponentWithId component, CancellationToken cancellationToken)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-			await session.Call(new DBSaveRequest { Component = component }, cancellationToken);
-		}
-
-		public static async ETVoid SaveLog(this DBProxyComponent self, ComponentWithId component)
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-			await session.Call(new DBSaveRequest { Component = component, CollectionName = "Log" });
-		}
-
-		public static ETTask<T> Query<T>(this DBProxyComponent self, long id) where T: ComponentWithId
-		{
-			string key = typeof (T).Name + id;
-			ETTaskCompletionSource<T> tcs = new ETTaskCompletionSource<T>();
-			if (self.TcsQueue.ContainsKey(key))
-			{
-				self.TcsQueue.Add(key, tcs);
-				return tcs.Task;
-			}
-			
-			self.TcsQueue.Add(key, tcs);
-			self.QueryInner<T>(id, key).Coroutine();
-			return tcs.Task;
-		}
-		
-		private static async ETVoid QueryInner<T>(this DBProxyComponent self, long id, string key) where T: ComponentWithId
-		{
-			try
-			{
-				Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-				DBQueryResponse dbQueryResponse = (DBQueryResponse)await session.Call(new DBQueryRequest { CollectionName = typeof(T).Name, Id = id });
-				T result = (T)dbQueryResponse.Component;
-
-				object[] tcss = self.TcsQueue.GetAll(key);
-				self.TcsQueue.Remove(key);
-			
-				foreach (ETTaskCompletionSource<T> tcs in tcss)
-				{
-					tcs.SetResult(result);
-				}
-			}
-			catch (Exception e)
-			{
-				object[] tcss = self.TcsQueue.GetAll(key);
-				self.TcsQueue.Remove(key);
-			
-				foreach (ETTaskCompletionSource<T> tcs in tcss)
-				{
-					tcs.SetException(e);
-				}
-			}
-		}
-		
-		/// <summary>
-		/// 根据查询表达式查询
-		/// </summary>
-		/// <param name="self"></param>
-		/// <param name="exp"></param>
-		/// <typeparam name="T"></typeparam>
-		/// <returns></returns>
-		public static async ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, Expression<Func<T ,bool>> exp) where T: ComponentWithId
-		{
-			ExpressionFilterDefinition<T> filter = new ExpressionFilterDefinition<T>(exp);
-			IBsonSerializerRegistry serializerRegistry = BsonSerializer.SerializerRegistry;
-			IBsonSerializer<T> documentSerializer = serializerRegistry.GetSerializer<T>();
-			string json = filter.Render(documentSerializer, serializerRegistry).ToJson();
-			return await self.Query<T>(json);
-		}
-
-		public static async ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, List<long> ids) where T : ComponentWithId
-		{
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-			DBQueryBatchResponse dbQueryBatchResponse = (DBQueryBatchResponse)await session.Call(new DBQueryBatchRequest { CollectionName = typeof(T).Name, IdList = ids });
-			return dbQueryBatchResponse.Components;
-		}
-
-		/// <summary>
-		/// 根据json查询条件查询
-		/// </summary>
-		/// <param name="self"></param>
-		/// <param name="json"></param>
-		/// <typeparam name="T"></typeparam>
-		/// <returns></returns>
-		public static ETTask<List<ComponentWithId>> Query<T>(this DBProxyComponent self, string json) where T : ComponentWithId
-		{
-			string key = typeof (T).Name + json;
-			ETTaskCompletionSource<List<ComponentWithId>> tcs = new ETTaskCompletionSource<List<ComponentWithId>>();
-			if (self.TcsQueue.ContainsKey(key))
-			{
-				self.TcsQueue.Add(key, tcs);
-				return tcs.Task;
-			}
-			
-			self.TcsQueue.Add(key, tcs);
-			self.QueryInner<T>(json, key).Coroutine();
-			return tcs.Task;
-		}
-		
-		private static async ETVoid QueryInner<T>(this DBProxyComponent self, string json, string key) where T : ComponentWithId
-		{
-			try
-			{
-				Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(self.dbAddress);
-				DBQueryJsonResponse dbQueryJsonResponse = (DBQueryJsonResponse)await session.Call(new DBQueryJsonRequest { CollectionName = typeof(T).Name, Json = json });
-				var result = dbQueryJsonResponse.Components;
-				
-				object[] tcss = self.TcsQueue.GetAll(key);
-				self.TcsQueue.Remove(key);
-			
-				foreach (ETTaskCompletionSource<List<ComponentWithId>> tcs in tcss)
-				{
-					tcs.SetResult(result);
-				}
-			}
-			catch (Exception e)
-			{
-				object[] tcss = self.TcsQueue.GetAll(key);
-				self.TcsQueue.Remove(key);
-			
-				foreach (ETTaskCompletionSource<List<ComponentWithId>> tcs in tcss)
-				{
-					tcs.SetException(e);
-				}
-			}
-		}
-	}
-}

+ 0 - 17
Server/Hotfix/Module/DB/DBQueryBatchRequestHandler.cs

@@ -1,17 +0,0 @@
-using System;
-using ETModel;
-
-namespace ETHotfix
-{
-	[MessageHandler(AppType.DB)]
-	public class DBQueryBatchRequestHandler : AMRpcHandler<DBQueryBatchRequest, DBQueryBatchResponse>
-	{
-		protected override async ETTask Run(Session session, DBQueryBatchRequest request, DBQueryBatchResponse response, Action reply)
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-			response.Components = await dbComponent.GetBatch(request.CollectionName, request.IdList);
-
-			reply();
-		}
-	}
-}

+ 0 - 19
Server/Hotfix/Module/DB/DBQueryJsonRequestHandler.cs

@@ -1,19 +0,0 @@
-using System;
-using System.Collections.Generic;
-using ETModel;
-
-namespace ETHotfix
-{
-	[MessageHandler(AppType.DB)]
-	public class DBQueryJsonRequestHandler : AMRpcHandler<DBQueryJsonRequest, DBQueryJsonResponse>
-	{
-		protected override async ETTask Run(Session session, DBQueryJsonRequest request, DBQueryJsonResponse response, Action reply)
-		{
-			List<ComponentWithId> components = await Game.Scene.GetComponent<DBComponent>().GetJson(request.CollectionName, request.Json);
-			response.Components = components;
-
-			reply();
-			await ETTask.CompletedTask;
-		}
-	}
-}

+ 0 - 18
Server/Hotfix/Module/DB/DBQueryRequestHandler.cs

@@ -1,18 +0,0 @@
-using System;
-using ETModel;
-
-namespace ETHotfix
-{
-	[MessageHandler(AppType.DB)]
-	public class DBQueryRequestHandler : AMRpcHandler<DBQueryRequest, DBQueryResponse>
-	{
-		protected override async ETTask Run(Session session, DBQueryRequest request, DBQueryResponse response, Action reply)
-		{
-			ComponentWithId component = await Game.Scene.GetComponent<DBComponent>().Get(request.CollectionName, request.Id);
-
-			response.Component = component;
-
-			reply();
-		}
-	}
-}

+ 0 - 23
Server/Hotfix/Module/DB/DBSaveBatchRequestHandler.cs

@@ -1,23 +0,0 @@
-using System;
-using ETModel;
-
-namespace ETHotfix
-{
-	[MessageHandler(AppType.DB)]
-	public class DBSaveBatchRequestHandler : AMRpcHandler<DBSaveBatchRequest, DBSaveBatchResponse>
-	{
-		protected override async ETTask Run(Session session, DBSaveBatchRequest request, DBSaveBatchResponse response, Action reply)
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-
-			if (string.IsNullOrEmpty(request.CollectionName))
-			{
-				request.CollectionName = request.Components[0].GetType().Name;
-			}
-
-			await dbComponent.AddBatch(request.Components, request.CollectionName);
-
-			reply();
-		}
-	}
-}

+ 0 - 21
Server/Hotfix/Module/DB/DBSaveRequestHandler.cs

@@ -1,21 +0,0 @@
-using System;
-using ETModel;
-
-namespace ETHotfix
-{
-	[MessageHandler(AppType.DB)]
-	public class DBSaveRequestHandler : AMRpcHandler<DBSaveRequest, DBSaveResponse>
-	{
-		protected override async ETTask Run(Session session, DBSaveRequest request, DBSaveResponse response, Action reply)
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-			if (string.IsNullOrEmpty(request.CollectionName))
-			{
-				request.CollectionName = request.Component.GetType().Name;
-			}
-
-			await dbComponent.Add(request.Component, request.CollectionName);
-			reply();
-		}
-	}
-}

+ 26 - 32
Server/Hotfix/Module/Demo/Actor_TransferHandler.cs

@@ -9,38 +9,32 @@ namespace ETHotfix
 	{
 		protected override async ETTask Run(Unit unit, Actor_TransferRequest request, Actor_TransferResponse response, Action reply)
 		{
-			long unitId = unit.Id;
-
-			// 先在location锁住unit的地址
-			await Game.Scene.GetComponent<LocationProxyComponent>().Lock(unitId, unit.InstanceId);
-
-			// 删除unit,让其它进程发送过来的消息找不到actor,重发
-			Game.EventSystem.Remove(unitId);
-			
-			long instanceId = unit.InstanceId;
-			
-			int mapIndex = request.MapIndex;
-
-			StartConfigComponent startConfigComponent = StartConfigComponent.Instance;
-
-			// 考虑AllServer情况
-			if (startConfigComponent.Count == 1)
-			{
-				mapIndex = 0;
-			}
-
-			// 传送到map
-			StartConfig mapConfig = startConfigComponent.MapConfigs[mapIndex];
-			IPEndPoint address = mapConfig.GetComponent<InnerConfig>().IPEndPoint;
-			Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(address);
-
-			// 只删除不disponse否则M2M_TrasferUnitRequest无法序列化Unit
-			Game.Scene.GetComponent<UnitComponent>().RemoveNoDispose(unitId);
-			M2M_TrasferUnitResponse m2m_TrasferUnitResponse = (M2M_TrasferUnitResponse)await session.Call(new M2M_TrasferUnitRequest() { Unit = unit });
-			unit.Dispose();
-
-			// 解锁unit的地址,并且更新unit的instanceId
-			await Game.Scene.GetComponent<LocationProxyComponent>().UnLock(unitId, instanceId, m2m_TrasferUnitResponse.InstanceId);
+			//long unitId = unit.Id;
+//
+			//// 先在location锁住unit的地址
+			//await Game.Scene.GetComponent<LocationProxyComponent>().Lock(unitId, unit.InstanceId);
+//
+			//// 删除unit,让其它进程发送过来的消息找不到actor,重发
+			//Game.EventSystem.Remove(unitId);
+			//
+			//long instanceId = unit.InstanceId;
+			//
+			//int mapIndex = request.MapIndex;
+//
+			//StartConfigComponent startConfigComponent = StartConfigComponent.Instance;
+//
+			//// 传送到map
+			//StartConfig mapConfig = startConfigComponent.MapConfigs[mapIndex];
+			//IPEndPoint address = mapConfig.GetComponent<InnerConfig>().IPEndPoint;
+			//Session session = Game.Scene.GetComponent<NetInnerComponent>().Get(address);
+//
+			//// 只删除不disponse否则M2M_TrasferUnitRequest无法序列化Unit
+			//Game.Scene.GetComponent<UnitComponent>().RemoveNoDispose(unitId);
+			//M2M_TrasferUnitResponse m2m_TrasferUnitResponse = (M2M_TrasferUnitResponse)await session.Call(new M2M_TrasferUnitRequest() { Unit = unit });
+			//unit.Dispose();
+//
+			//// 解锁unit的地址,并且更新unit的instanceId
+			//await Game.Scene.GetComponent<LocationProxyComponent>().UnLock(unitId, instanceId, m2m_TrasferUnitResponse.InstanceId);
 
 			reply();
 		}

+ 5 - 4
Server/Hotfix/Module/Demo/C2G_EnterMapHandler.cs

@@ -4,16 +4,17 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Gate)]
+	[MessageHandler]
 	public class C2G_EnterMapHandler : AMRpcHandler<C2G_EnterMap, G2C_EnterMap>
 	{
 		protected override async ETTask Run(Session session, C2G_EnterMap request, G2C_EnterMap response, Action reply)
 		{
 			Player player = session.GetComponent<SessionPlayerComponent>().Player;
 			// 在map服务器上创建战斗Unit
-			IPEndPoint mapAddress = StartConfigComponent.Instance.MapConfigs[0].GetComponent<InnerConfig>().IPEndPoint;
-			Session mapSession = Game.Scene.GetComponent<NetInnerComponent>().Get(mapAddress);
-			M2G_CreateUnit createUnit = (M2G_CreateUnit)await mapSession.Call(new G2M_CreateUnit() { PlayerId = player.Id, GateSessionId = session.InstanceId });
+			long mapInstanceId = StartConfigComponent.Instance.GetByName("Map").SceneInstanceId;
+			M2G_CreateUnit createUnit = (M2G_CreateUnit)await ActorMessageSenderComponent.Instance.Call(
+				mapInstanceId, 
+				new G2M_CreateUnit() { PlayerId = player.Id, GateSessionId = session.InstanceId });
 			player.UnitId = createUnit.UnitId;
 			response.UnitId = createUnit.UnitId;
 			reply();

+ 3 - 3
Server/Hotfix/Module/Demo/C2G_LoginGateHandler.cs

@@ -3,7 +3,7 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Gate)]
+	[MessageHandler]
 	public class C2G_LoginGateHandler : AMRpcHandler<C2G_LoginGate, G2C_LoginGate>
 	{
 		protected override async ETTask Run(Session session, C2G_LoginGate request, G2C_LoginGate response, Action reply)
@@ -16,10 +16,10 @@ namespace ETHotfix
 				reply();
 				return;
 			}
-			Player player = ComponentFactory.Create<Player, string>(account);
+			Player player = EntityFactory.Create<Player, string>(Game.Scene, account);
 			Game.Scene.GetComponent<PlayerComponent>().Add(player);
 			session.AddComponent<SessionPlayerComponent>().Player = player;
-			session.AddComponent<MailBoxComponent, string>(MailboxType.GateSession);
+			session.AddComponent<MailBoxComponent, MailboxType>(MailboxType.GateSession);
 
 			response.PlayerId = player.Id;
 			reply();

+ 3 - 3
Server/Hotfix/Module/Demo/C2R_LoginHandler.cs

@@ -4,7 +4,7 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Realm)]
+	[MessageHandler]
 	public class C2R_LoginHandler : AMRpcHandler<C2R_Login, R2C_Login>
 	{
 		protected override async ETTask Run(Session session, C2R_Login request, R2C_Login response, Action reply)
@@ -17,9 +17,9 @@ namespace ETHotfix
 			//}
 
 			// 随机分配一个Gate
-			StartConfig config = Game.Scene.GetComponent<RealmGateAddressComponent>().GetAddress();
+			StartConfig config = RealmGateAddressHelper.GetGate();
 			//Log.Debug($"gate address: {MongoHelper.ToJson(config)}");
-			IPEndPoint innerAddress = config.GetComponent<InnerConfig>().IPEndPoint;
+			string innerAddress = config.GetComponent<InnerConfig>().Address;
 			Session gateSession = Game.Scene.GetComponent<NetInnerComponent>().Get(innerAddress);
 
 			// 向gate请求一个key,客户端可以拿着这个key连接gate

+ 9 - 8
Server/Hotfix/Module/Demo/G2M_CreateUnitHandler.cs

@@ -5,19 +5,20 @@ using UnityEngine;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Map)]
-	public class G2M_CreateUnitHandler : AMRpcHandler<G2M_CreateUnit, M2G_CreateUnit>
+	[MessageHandler]
+	public class G2M_CreateUnitHandler : AMActorRpcHandler<Scene, G2M_CreateUnit, M2G_CreateUnit>
 	{
-		protected override async ETTask Run(Session session, G2M_CreateUnit request, M2G_CreateUnit response, Action reply)
+		protected override async ETTask Run(Scene scene, G2M_CreateUnit request, M2G_CreateUnit response, Action reply)
 		{
-			Unit unit = ComponentFactory.CreateWithId<Unit>(IdGenerater.GenerateId());
+			Unit unit = EntityFactory.CreateWithId<Unit>(scene, IdGenerater.GenerateId());
 			unit.AddComponent<MoveComponent>();
 			unit.AddComponent<UnitPathComponent>();
 			unit.Position = new Vector3(-10, 0, -10);
-			
-			await unit.AddComponent<MailBoxComponent>().AddLocation();
+
+			unit.AddComponent<MailBoxComponent>();
+			await unit.AddLocation();
 			unit.AddComponent<UnitGateComponent, long>(request.GateSessionId);
-			Game.Scene.GetComponent<UnitComponent>().Add(unit);
+			scene.GetComponent<UnitComponent>().Add(unit);
 			response.UnitId = unit.Id;
 			
 			
@@ -33,7 +34,7 @@ namespace ETHotfix
 				unitInfo.UnitId = u.Id;
 				createUnits.Units.Add(unitInfo);
 			}
-			MessageHelper.Broadcast(createUnits);
+			MessageHelper.Broadcast(unit, createUnits);
 			
 			reply();
 		}

+ 4 - 5
Server/Hotfix/Module/Demo/M2M_TrasferUnitRequest.cs

@@ -3,18 +3,17 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Map)]
-	public class M2M_TrasferUnitRequestHandler : AMRpcHandler<M2M_TrasferUnitRequest, M2M_TrasferUnitResponse>
+	[MessageHandler]
+	public class M2M_TrasferUnitRequestHandler : AMActorRpcHandler<Scene, M2M_TrasferUnitRequest, M2M_TrasferUnitResponse>
 	{
-		protected override async ETTask Run(Session session, M2M_TrasferUnitRequest request, M2M_TrasferUnitResponse response, Action reply)
+		protected override async ETTask Run(Scene scene, M2M_TrasferUnitRequest request, M2M_TrasferUnitResponse response, Action reply)
 		{
 			Unit unit = request.Unit;
 			// 将unit加入事件系统
-			Game.EventSystem.Add(unit);
 			Log.Debug(MongoHelper.ToJson(request.Unit));
 			// 这里不需要注册location,因为unlock会更新位置
 			unit.AddComponent<MailBoxComponent>();
-			Game.Scene.GetComponent<UnitComponent>().Add(unit);
+			scene.GetComponent<UnitComponent>().Add(unit);
 			response.InstanceId = unit.InstanceId;
 			reply();
 			await ETTask.CompletedTask;

+ 62 - 19
Server/Hotfix/Module/Demo/MessageHelper.cs

@@ -2,23 +2,66 @@
 
 namespace ETHotfix
 {
-	public static class MessageHelper
-	{
-		public static void Broadcast(IActorMessage message)
-		{
-			Unit[] units = Game.Scene.GetComponent<UnitComponent>().GetAll();
-			ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent<ActorMessageSenderComponent>();
-			foreach (Unit unit in units)
-			{
-				UnitGateComponent unitGateComponent = unit.GetComponent<UnitGateComponent>();
-				if (unitGateComponent.IsDisconnect)
-				{
-					continue;
-				}
+    public static class MessageHelper
+    {
+        public static void Broadcast(Unit unit, IActorMessage message)
+        {
+            var units = unit.Domain.GetComponent<UnitComponent>().GetAll();
 
-				ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(unitGateComponent.GateSessionActorId);
-				actorMessageSender.Send(message);
-			}
-		}
-	}
-}
+            if (units == null) return;
+
+            foreach (Unit u in units)
+            {
+                UnitGateComponent unitGateComponent = u.GetComponent<UnitGateComponent>();
+                if (unitGateComponent.IsDisconnect)
+                {
+                    continue;
+                }
+                SendActor(unitGateComponent.GateSessionActorId, message);
+            }
+        }
+        
+        
+        /// <summary>
+        /// 发送协议给ActorLocation
+        /// </summary>
+        /// <param name="id">注册Actor的Id</param>
+        /// <param name="message"></param>
+        public static void SendToLocationActor(long id, IActorLocationMessage message)
+        {
+            ActorLocationSenderComponent.Instance.Send(id, message);
+        }
+        
+        /// <summary>
+        /// 发送协议给Actor
+        /// </summary>
+        /// <param name="actorId">注册Actor的InstanceId</param>
+        /// <param name="message"></param>
+        public static void SendActor(long actorId, IActorMessage message)
+        {
+            ActorMessageSenderComponent.Instance.Send(actorId, message);
+        }
+        
+        /// <summary>
+        /// 发送RPC协议给Actor
+        /// </summary>
+        /// <param name="actorId">注册Actor的InstanceId</param>
+        /// <param name="message"></param>
+        /// <returns></returns>
+        public static async ETTask<IActorResponse> CallActor(long actorId, IActorRequest message)
+        {
+            return await ActorMessageSenderComponent.Instance.Call(actorId, message);
+        }
+        
+        /// <summary>
+        /// 发送RPC协议给ActorLocation
+        /// </summary>
+        /// <param name="id">注册Actor的Id</param>
+        /// <param name="message"></param>
+        /// <returns></returns>
+        public static async ETTask<IActorResponse> CallLocationActor(long id, IActorLocationRequest message)
+        {
+            return await ActorLocationSenderComponent.Instance.Call(id, message);
+        }
+    }
+}

+ 4 - 4
Server/Hotfix/Module/Demo/R2G_GetLoginKeyHandler.cs

@@ -3,13 +3,13 @@ using ETModel;
 
 namespace ETHotfix
 {
-	[MessageHandler(AppType.Gate)]
-	public class R2G_GetLoginKeyHandler : AMRpcHandler<R2G_GetLoginKey, G2R_GetLoginKey>
+	[MessageHandler]
+	public class R2G_GetLoginKeyHandler : AMActorRpcHandler<Scene, R2G_GetLoginKey, G2R_GetLoginKey>
 	{
-		protected override async ETTask Run(Session session, R2G_GetLoginKey request, G2R_GetLoginKey response, Action reply)
+		protected override async ETTask Run(Scene scene, R2G_GetLoginKey request, G2R_GetLoginKey response, Action reply)
 		{
 			long key = RandomHelper.RandInt64();
-			Game.Scene.GetComponent<GateSessionKeyComponent>().Add(key, request.Account);
+			scene.GetComponent<GateSessionKeyComponent>().Add(key, request.Account);
 			response.Key = key;
 			reply();
 			await ETTask.CompletedTask;

+ 0 - 30
Server/Hotfix/Module/Demo/RealmGateAddressComponentSystem.cs

@@ -1,30 +0,0 @@
-using ETModel;
-
-namespace ETHotfix
-{
-	[ObjectSystem]
-	public class RealmGateAddressComponentSystem : StartSystem<RealmGateAddressComponent>
-	{
-		public override void Start(RealmGateAddressComponent self)
-		{
-			self.Start();
-		}
-	}
-	
-	public static class RealmGateAddressComponentEx
-	{
-		public static void Start(this RealmGateAddressComponent component)
-		{
-			StartConfig[] startConfigs = StartConfigComponent.Instance.GetAll();
-			foreach (StartConfig config in startConfigs)
-			{
-				if (!config.AppType.Is(AppType.Gate))
-				{
-					continue;
-				}
-				
-				component.GateAddress.Add(config);
-			}
-		}
-	}
-}

+ 16 - 0
Server/Hotfix/Module/Demo/RealmGateAddressHelper.cs

@@ -0,0 +1,16 @@
+using ETModel;
+
+namespace ETHotfix
+{
+	public static class RealmGateAddressHelper
+	{
+		public static StartConfig GetGate()
+		{
+			int count = StartConfigComponent.Instance.Gates.Count;
+
+			int n = RandomHelper.RandomNumber(0, count);
+
+			return StartConfigComponent.Instance.Gates[n];
+		}
+	}
+}

+ 1 - 2
Server/Hotfix/Module/Demo/SessionPlayerComponentSystem.cs

@@ -8,8 +8,7 @@ namespace ETHotfix
 		public override void Destroy(SessionPlayerComponent self)
 		{
 			// 发送断线消息
-			ActorLocationSender actorLocationSender = Game.Scene.GetComponent<ActorLocationSenderComponent>().Get(self.Player.UnitId);
-			actorLocationSender.Send(new G2M_SessionDisconnect());
+			ActorLocationSenderComponent.Instance.Send(self.Player.UnitId, new G2M_SessionDisconnect());
 			Game.Scene.GetComponent<PlayerComponent>()?.Remove(self.Player.Id);
 		}
 	}

+ 4 - 4
Server/Hotfix/Module/Demo/UnitPathComponentSystem.cs

@@ -23,7 +23,7 @@ namespace ETHotfix
                     self.BroadcastPath(path, i, 3);
                 }
                 Vector3 v3 = path[i];
-                await self.Entity.GetComponent<MoveComponent>().MoveToAsync(v3, self.CancellationTokenSource.Token);
+                await self.Parent.GetComponent<MoveComponent>().MoveToAsync(v3, self.CancellationTokenSource.Token);
             }
         }
         
@@ -40,12 +40,12 @@ namespace ETHotfix
             
             
             PathfindingComponent pathfindingComponent = Game.Scene.GetComponent<PathfindingComponent>();
-            self.ABPath = ComponentFactory.Create<ABPathWrap, Vector3, Vector3>(unit.Position, new Vector3(target.x, target.y, target.z));
+            self.ABPath = EntityFactory.Create<ABPathWrap, Vector3, Vector3>(self.Domain, unit.Position, new Vector3(target.x, target.y, target.z));
             pathfindingComponent.Search(self.ABPath);
             Log.Debug($"find result: {self.ABPath.Result.ListToString()}");
             
             self.CancellationTokenSource?.Cancel();
-            self.CancellationTokenSource = new CancellationTokenSource();
+            self.CancellationTokenSource = EntityFactory.Create<ETCancellationTokenSource>(self.Domain);
             await self.MoveAsync(self.ABPath.Result);
             self.CancellationTokenSource.Dispose();
             self.CancellationTokenSource = null;
@@ -73,7 +73,7 @@ namespace ETHotfix
                 m2CPathfindingResult.Ys.Add(v.y);
                 m2CPathfindingResult.Zs.Add(v.z);
             }
-            MessageHelper.Broadcast(m2CPathfindingResult);
+            MessageHelper.Broadcast(unit, m2CPathfindingResult);
         }
     }
 }

+ 32 - 80
Server/Hotfix/Module/Message/InnerMessageDispatcher.cs

@@ -2,84 +2,36 @@
 
 namespace ETHotfix
 {
-	public class InnerMessageDispatcher: IMessageDispatcher
-	{
-		public void Dispatch(Session session, ushort opcode, object message)
-		{
-			// 收到actor消息,放入actor队列
-			switch (message)
-			{
-				case IActorRequest iActorRequest:
-				{
-					HandleIActorRequest(session, iActorRequest).Coroutine();
-					break;
-				}
-				case IActorMessage iactorMessage:
-				{
-					HandleIActorMessage(session, iactorMessage).Coroutine();
-					break;
-				}
-				default:
-				{
-					Game.Scene.GetComponent<MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message));
-					break;
-				}
-			}
-		}
+    public class InnerMessageDispatcher: IMessageDispatcher
+    {
+        public void Dispatch(Session session, ushort opcode, object message)
+        {
+            // 收到actor消息,放入actor队列
+            switch (message)
+            {
+                case IActorRequest iActorRequest:
+                {
+                    InnerMessageDispatcherHelper.HandleIActorRequest(session, iActorRequest).Coroutine();
+                    return;
+                }
+                case IActorMessage iactorMessage:
+                {
+                    InnerMessageDispatcherHelper.HandleIActorMessage(session, iactorMessage).Coroutine();
+                    return;
+                }
+                case IActorResponse iActorResponse:
+                {
+                    InnerMessageDispatcherHelper.HandleIActorResponse(session, iActorResponse).Coroutine();
+                    return;
+                }
+                default:
+                {
+                    MessageDispatcherComponent.Instace.Handle(session, new MessageInfo(opcode, message));
+                    break;
+                }
+            }
+        }
+		
 
-		private async ETVoid HandleIActorRequest(Session session, IActorRequest message)
-		{
-			using (await CoroutineLockComponent.Instance.Wait(message.ActorId))
-			{
-				Entity entity = (Entity)Game.EventSystem.Get(message.ActorId);
-				if (entity == null)
-				{
-					Log.Warning($"not found actor: {message}");
-					ActorResponse response = new ActorResponse
-					{
-						Error = ErrorCode.ERR_NotFoundActor,
-						RpcId = message.RpcId
-					};
-					session.Reply(response);
-					return;
-				}
-	
-				MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
-				if (mailBoxComponent == null)
-				{
-					ActorResponse response = new ActorResponse
-					{
-						Error = ErrorCode.ERR_ActorNoMailBoxComponent,
-						RpcId = message.RpcId
-					};
-					session.Reply(response);
-					Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {message}");
-					return;
-				}
-				
-				await mailBoxComponent.Add(session, message);
-			}
-		}
-
-		private async ETVoid HandleIActorMessage(Session session, IActorMessage message)
-		{
-			using (await CoroutineLockComponent.Instance.Wait(message.ActorId))
-			{
-				Entity entity = (Entity)Game.EventSystem.Get(message.ActorId);
-				if (entity == null)
-				{
-					Log.Error($"not found actor: {message}");
-					return;
-				}
-	
-				MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
-				if (mailBoxComponent == null)
-				{
-					Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {message}");
-					return;
-				}
-				await mailBoxComponent.Add(session, message);
-			}
-		}
-	}
-}
+    }
+}

+ 75 - 0
Server/Hotfix/Module/Message/InnerMessageDispatcherHelper.cs

@@ -0,0 +1,75 @@
+using ETModel;
+
+ namespace ETHotfix
+{
+    public static class InnerMessageDispatcherHelper
+    {
+        public static async ETVoid HandleIActorResponse(Session session, IActorResponse iActorResponse)
+		{
+			ActorMessageSenderComponent.Instance.RunMessage(iActorResponse);
+		}
+
+		public static async ETVoid HandleIActorRequest(Session session, IActorRequest iActorRequest)
+		{
+			long replyId = IdGenerater.GetProcessId(iActorRequest.ActorId);
+			iActorRequest.ActorId = iActorRequest.ActorId & IdGenerater.HeadMask | IdGenerater.Head;
+			using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Mailbox, iActorRequest.ActorId))
+			{
+				string address = StartConfigComponent.Instance.GetProcessInnerAddress(replyId);
+				Session ss = NetInnerComponent.Instance.Get(address);
+				Entity entity = Game.EventSystem.Get(iActorRequest.ActorId);
+				if (entity == null)
+				{
+					Log.Warning($"not found actor: {MongoHelper.ToJson(iActorRequest)}");
+					ActorResponse response = new ActorResponse
+					{
+						Error = ErrorCode.ERR_NotFoundActor,
+						RpcId = iActorRequest.RpcId,
+					};
+					ss.Reply(response);
+					return;
+				}
+	
+				MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
+				if (mailBoxComponent == null)
+				{
+					ActorResponse response = new ActorResponse
+					{
+						Error = ErrorCode.ERR_ActorNoMailBoxComponent,
+						RpcId = iActorRequest.RpcId,
+					};
+					ss.Reply(response);
+					Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {iActorRequest}");
+					return;
+				}
+				
+				await MailboxDispatcherComponent.Instance.Handle(entity, mailBoxComponent.MailboxType, ss, iActorRequest);
+			}
+		}
+
+		public static async ETVoid HandleIActorMessage(Session session, IActorMessage iActorMessage)
+		{
+			long replyId = IdGenerater.GetProcessId(iActorMessage.ActorId);
+			iActorMessage.ActorId = iActorMessage.ActorId & IdGenerater.HeadMask | IdGenerater.Head;
+			using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Mailbox, iActorMessage.ActorId))
+			{
+				Entity entity = Game.EventSystem.Get(iActorMessage.ActorId);
+				if (entity == null)
+				{
+					Log.Error($"not found actor: {MongoHelper.ToJson(iActorMessage)}");
+					return;
+				}
+	
+				MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
+				if (mailBoxComponent == null)
+				{
+					Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {iActorMessage}");
+					return;
+				}
+				
+				Session ss = NetInnerComponent.Instance.Get(replyId);
+				await MailboxDispatcherComponent.Instance.Handle(entity, mailBoxComponent.MailboxType, ss, iActorMessage);
+			}
+		}
+    }
+}

+ 13 - 16
Server/Hotfix/Module/Message/MessageDispatherComponentSystem.cs

@@ -9,6 +9,7 @@ namespace ETHotfix
 	{
 		public override void Awake(MessageDispatcherComponent self)
 		{
+			MessageDispatcherComponent.Instace = self;
 			self.Load();
 		}
 	}
@@ -21,6 +22,16 @@ namespace ETHotfix
 			self.Load();
 		}
 	}
+	
+	[ObjectSystem]
+	public class MessageDispatcherComponentDestroySystem: DestroySystem<MessageDispatcherComponent>
+	{
+		public override void Destroy(MessageDispatcherComponent self)
+		{
+			MessageDispatcherComponent.Instace = null;
+			self.Handlers.Clear();
+		}
+	}
 
 	/// <summary>
 	/// 消息分发组件
@@ -31,24 +42,10 @@ namespace ETHotfix
 		{
 			self.Handlers.Clear();
 
-			AppType appType = StartConfigComponent.Instance.StartConfig.AppType;
-
-			List<Type> types = Game.EventSystem.GetTypes(typeof(MessageHandlerAttribute));
+			HashSet<Type> types = Game.EventSystem.GetTypes(typeof(MessageHandlerAttribute));
 
 			foreach (Type type in types)
 			{
-				object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-
-				MessageHandlerAttribute messageHandlerAttribute = attrs[0] as MessageHandlerAttribute;
-				if (!messageHandlerAttribute.Type.Is(appType))
-				{
-					continue;
-				}
-
 				IMHandler iMHandler = Activator.CreateInstance(type) as IMHandler;
 				if (iMHandler == null)
 				{
@@ -57,7 +54,7 @@ namespace ETHotfix
 				}
 
 				Type messageType = iMHandler.GetMessageType();
-				ushort opcode = Game.Scene.GetComponent<OpcodeTypeComponent>().GetOpcode(messageType);
+				ushort opcode = OpcodeTypeComponent.Instance.GetOpcode(messageType);
 				if (opcode == 0)
 				{
 					Log.Error($"消息opcode为0: {messageType.Name}");

+ 0 - 2
Server/Hotfix/Module/Message/NetInnerComponentSystem.cs

@@ -47,7 +47,6 @@ namespace ETHotfix
 			self.Awake(NetworkProtocol.TCP, Packet.PacketSizeLength4);
 			self.MessagePacker = new MongoPacker();
 			self.MessageDispatcher = new InnerMessageDispatcher();
-			self.AppType = StartConfigComponent.Instance.StartConfig.AppType;
 		}
 
 		public static void Awake(this NetInnerComponent self, string address)
@@ -55,7 +54,6 @@ namespace ETHotfix
 			self.Awake(NetworkProtocol.TCP, address, Packet.PacketSizeLength4);
 			self.MessagePacker = new MongoPacker();
 			self.MessageDispatcher = new InnerMessageDispatcher();
-			self.AppType = StartConfigComponent.Instance.StartConfig.AppType;
 		}
 
 		public static void Update(this NetInnerComponent self)

+ 6 - 9
Server/Hotfix/Module/Message/OuterMessageDispatcher.cs

@@ -11,17 +11,16 @@ namespace ETHotfix
 		
 		public async ETVoid DispatchAsync(Session session, ushort opcode, object message)
 		{
+			long unitId = session.GetComponent<SessionPlayerComponent>().Player.UnitId;
+			
 			// 根据消息接口判断是不是Actor消息,不同的接口做不同的处理
 			switch (message)
 			{
 				case IActorLocationRequest actorLocationRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端
 				{
-					long unitId = session.GetComponent<SessionPlayerComponent>().Player.UnitId;
-					ActorLocationSender actorLocationSender = Game.Scene.GetComponent<ActorLocationSenderComponent>().Get(unitId);
-
 					int rpcId = actorLocationRequest.RpcId; // 这里要保存客户端的rpcId
 					long instanceId = session.InstanceId;
-					IResponse response = await actorLocationSender.Call(actorLocationRequest);
+					IResponse response = await ActorLocationSenderComponent.Instance.Call(unitId, actorLocationRequest);
 					response.RpcId = rpcId;
 
 					// session可能已经断开了,所以这里需要判断
@@ -29,14 +28,11 @@ namespace ETHotfix
 					{
 						session.Reply(response);
 					}
-					
 					break;
 				}
 				case IActorLocationMessage actorLocationMessage:
 				{
-					long unitId = session.GetComponent<SessionPlayerComponent>().Player.UnitId;
-					ActorLocationSender actorLocationSender = Game.Scene.GetComponent<ActorLocationSenderComponent>().Get(unitId);
-					actorLocationSender.Send(actorLocationMessage);
+					ActorLocationSenderComponent.Instance.Send(unitId, actorLocationMessage);
 					break;
 				}
 				case IActorRequest actorRequest:  // 分发IActorRequest消息,目前没有用到,需要的自己添加
@@ -47,10 +43,11 @@ namespace ETHotfix
 				{
 					break;
 				}
+				
 				default:
 				{
 					// 非Actor消息
-					Game.Scene.GetComponent<MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message));
+					MessageDispatcherComponent.Instace.Handle(session, new MessageInfo(opcode, message));
 					break;
 				}
 			}

+ 22 - 0
Server/Hotfix/Module/Scene/AfterScenesAdd_CreateScene.cs

@@ -0,0 +1,22 @@
+using ETModel;
+
+namespace ETHotfix
+{
+    [Event(EventIdType.AfterScenesAdd)]
+    public class AfterScenesAdd_CreateScene: AEvent
+    {
+        public override void Run()
+        {
+            RunInner().Coroutine();
+        }
+
+        public async ETVoid RunInner()
+        {
+            foreach (StartConfig startConfig in StartConfigComponent.Instance.StartConfig.List)
+            {
+                SceneConfig sceneConfig = startConfig.GetComponent<SceneConfig>();
+                await SceneFactory.Create(Game.Scene, startConfig.Id, sceneConfig.Name, sceneConfig.SceneType);    
+            }
+        }
+    }
+}

+ 41 - 0
Server/Hotfix/Module/Scene/SceneFactory.cs

@@ -0,0 +1,41 @@
+using ETModel;
+
+namespace ETHotfix
+{
+    public static class SceneFactory
+    {
+        public static async ETTask<Scene> Create(Entity parent, string name, SceneType sceneType)
+        {
+            return await Create(parent, IdGenerater.GenerateSceneId(), name, sceneType);
+        }
+        
+        public static async ETTask<Scene> Create(Entity parent, long id, string name, SceneType sceneType)
+        {
+            Scene scene = EntityFactory.CreateScene(id, name, sceneType);
+            scene.Parent = parent;
+
+            scene.AddComponent<MailBoxComponent, MailboxType>(MailboxType.UnOrderMessageDispatcher);
+
+            switch (scene.SceneType)
+            {
+                case SceneType.Realm:
+                    break;
+                case SceneType.Gate:
+                    scene.AddComponent<GateSessionKeyComponent>();
+                    break;
+                case SceneType.Map:
+                    scene.AddComponent<UnitComponent>();
+                    if (name == "GateMap")
+                    {
+                        return scene;
+                    }
+                    break;
+                case SceneType.Location:
+                    scene.AddComponent<LocationComponent>();
+                    break;
+            }
+
+            return scene;
+        }
+    }
+}

+ 1 - 1
Server/Hotfix/Server.Hotfix.csproj

@@ -1,6 +1,6 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
-    <TargetFramework>netcoreapp2.2</TargetFramework>
+    <TargetFramework>netcoreapp3.0</TargetFramework>
     <AssemblyName>Hotfix</AssemblyName>
     <RootNamespace>ETHotfix</RootNamespace>
     <LangVersion>7.3</LangVersion>

+ 1 - 0
Server/Model/Base/Event/EventIdType.cs

@@ -3,5 +3,6 @@
 	public static class EventIdType
 	{
 		public const string NumbericChange = "NumbericChange";
+		public const string AfterScenesAdd = "AfterScenesAdd";
 	}
 }

+ 6 - 0
Server/Model/Base/Object/IDBCollection.cs

@@ -0,0 +1,6 @@
+namespace ETModel
+{
+    public interface IDBCollection
+    {
+    }
+}

+ 0 - 98
Server/Model/Component/AppManagerComponent.cs

@@ -1,98 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Runtime.InteropServices;
-
-namespace ETModel
-{
-	[ObjectSystem]
-	public class AppManagerComponentAwakeSystem : AwakeSystem<AppManagerComponent>
-	{
-		public override void Awake(AppManagerComponent self)
-		{
-			self.Awake();
-		}
-	}
-
-	public class AppManagerComponent: Component
-	{
-		private readonly Dictionary<int, Process> processes = new Dictionary<int, Process>();
-
-		public void Awake()
-		{
-			string[] ips = NetHelper.GetAddressIPs();
-			StartConfig[] startConfigs = StartConfigComponent.Instance.GetAll();
-			
-			foreach (StartConfig startConfig in startConfigs)
-			{
-				Game.Scene.GetComponent<TimerComponent>().WaitAsync(100);
-				
-				if (!ips.Contains(startConfig.ServerIP) && startConfig.ServerIP != "*")
-				{
-					continue;
-				}
-
-				if (startConfig.AppType.Is(AppType.Manager))
-				{
-					continue;
-				}
-
-				StartProcess(startConfig.AppId);
-			}
-
-			this.WatchProcessAsync().Coroutine();
-		}
-
-		private void StartProcess(int appId)
-		{
-			OptionComponent optionComponent = Game.Scene.GetComponent<OptionComponent>();
-			StartConfigComponent startConfigComponent = StartConfigComponent.Instance;
-			string configFile = optionComponent.Options.Config;
-			StartConfig startConfig = startConfigComponent.Get(appId);
-			const string exe = "dotnet";
-			string arguments = $"App.dll --appId={startConfig.AppId} --appType={startConfig.AppType} --config={configFile}";
-
-			Log.Info($"{exe} {arguments}");
-			try
-			{
-				Process process = ProcessHelper.Run(exe, arguments);
-				this.processes.Add(startConfig.AppId, process);
-			}
-			catch (Exception e)
-			{
-				Log.Error(e);
-			}
-		}
-
-		/// <summary>
-		/// 监控启动的进程,如果进程挂掉了,重新拉起
-		/// </summary>
-		private async ETVoid WatchProcessAsync()
-		{
-			long instanceId = this.InstanceId;
-			
-			while (true)
-			{
-				await Game.Scene.GetComponent<TimerComponent>().WaitAsync(5000);
-
-				if (this.InstanceId != instanceId)
-				{
-					return;
-				}
-
-				foreach (int appId in this.processes.Keys.ToArray())
-				{
-					Process process = this.processes[appId];
-					if (!process.HasExited)
-					{
-						continue;
-					}
-					this.processes.Remove(appId);
-					process.Dispose();
-					this.StartProcess(appId);
-				}
-			}
-		}
-	}
-}

+ 1 - 1
Server/Model/Component/KVComponent.cs

@@ -6,7 +6,7 @@ namespace ETModel
 	/// <summary>
 	/// Key Value组件用于保存一些数据
 	/// </summary>
-	public class KVComponent: Component
+	public class KVComponent: Entity
 	{
 		[BsonElement]
 		private readonly Dictionary<string, object> kv = new Dictionary<string, object>();

+ 1 - 1
Server/Model/Component/OptionComponent.cs

@@ -12,7 +12,7 @@ namespace ETModel
 		}
 	}
 	
-	public class OptionComponent : Component
+	public class OptionComponent : Entity
 	{
 		public Options Options { get; set; }
 

+ 2 - 2
Server/Model/Component/ReplComponent.cs

@@ -17,7 +17,7 @@ namespace ETModel
         }
     }
     
-    public class ReplComponent: Component
+    public class ReplComponent: Entity
     {
         public ScriptOptions ScriptOptions;
         public ScriptState ScriptState;
@@ -28,7 +28,7 @@ namespace ETModel
             {
                 case "exit":
                 {
-                    this.Entity.RemoveComponent<ReplComponent>();
+                    this.Parent.RemoveComponent<ReplComponent>();
                     return true;
                 }
                 case "reset":

+ 1 - 1
Server/Model/Component/RobotComponent.cs

@@ -1,6 +1,6 @@
 namespace ETModel
 {
-	public class RobotComponent: Component
+	public class RobotComponent: Entity
 	{
 		public override void Dispose()
 		{

+ 169 - 141
Server/Model/Component/StartConfigComponent.cs

@@ -1,147 +1,175 @@
 using System;
 using System.Collections.Generic;
-using System.IO;
-using System.Linq;
 using System.Net;
 
 namespace ETModel
 {
-	[ObjectSystem]
-	public class StartConfigComponentSystem : AwakeSystem<StartConfigComponent, string, int>
-	{
-		public override void Awake(StartConfigComponent self, string a, int b)
-		{
-			self.Awake(a, b);
-		}
-	}
-	
-	public class StartConfigComponent: Component
-	{
-		public static StartConfigComponent Instance { get; private set; }
-		
-		private Dictionary<int, StartConfig> configDict;
-		
-		private Dictionary<int, IPEndPoint> innerAddressDict = new Dictionary<int, IPEndPoint>();
-		
-		public StartConfig StartConfig { get; private set; }
-
-		public StartConfig DBConfig { get; private set; }
-
-		public StartConfig RealmConfig { get; private set; }
-
-		public StartConfig LocationConfig { get; private set; }
-
-		public List<StartConfig> MapConfigs { get; private set; }
-
-		public List<StartConfig> GateConfigs { get; private set; }
-
-		public void Awake(string path, int appId)
-		{
-			Instance = this;
-			
-			this.configDict = new Dictionary<int, StartConfig>();
-			this.MapConfigs = new List<StartConfig>();
-			this.GateConfigs = new List<StartConfig>();
-
-			string[] ss = File.ReadAllText(path).Split('\n');
-			foreach (string s in ss)
-			{
-				string s2 = s.Trim();
-				if (s2 == "")
-				{
-					continue;
-				}
-				try
-				{
-					StartConfig startConfig = MongoHelper.FromJson<StartConfig>(s2);
-					this.configDict.Add(startConfig.AppId, startConfig);
-
-					InnerConfig innerConfig = startConfig.GetComponent<InnerConfig>();
-					if (innerConfig != null)
-					{
-						this.innerAddressDict.Add(startConfig.AppId, innerConfig.IPEndPoint);
-					}
-
-					if (startConfig.AppType.Is(AppType.Realm))
-					{
-						this.RealmConfig = startConfig;
-					}
-
-					if (startConfig.AppType.Is(AppType.Location))
-					{
-						this.LocationConfig = startConfig;
-					}
-
-					if (startConfig.AppType.Is(AppType.DB))
-					{
-						this.DBConfig = startConfig;
-					}
-
-					if (startConfig.AppType.Is(AppType.Map))
-					{
-						this.MapConfigs.Add(startConfig);
-					}
-
-					if (startConfig.AppType.Is(AppType.Gate))
-					{
-						this.GateConfigs.Add(startConfig);
-					}
-				}
-				catch (Exception e)
-				{
-					Log.Error($"config错误: {s2} {e}");
-				}
-			}
-
-			this.StartConfig = this.Get(appId);
-		}
-
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-			base.Dispose();
-			
-			Instance = null;
-		}
-
-		public StartConfig Get(int id)
-		{
-			try
-			{
-				return this.configDict[id];
-			}
-			catch (Exception e)
-			{
-				throw new Exception($"not found startconfig: {id}", e);
-			}
-		}
-		
-		public IPEndPoint GetInnerAddress(int id)
-		{
-			try
-			{
-				return this.innerAddressDict[id];
-			}
-			catch (Exception e)
-			{
-				throw new Exception($"not found innerAddress: {id}", e);
-			}
-		}
-
-		public StartConfig[] GetAll()
-		{
-			return this.configDict.Values.ToArray();
-		}
-
-		public int Count
-		{
-			get
-			{
-				return this.configDict.Count;
-			}
-		}
-	}
-}
+    [ObjectSystem]
+    public class StartConfigComponentSystem: AwakeSystem<StartConfigComponent, StartConfig, long>
+    {
+        public override void Awake(StartConfigComponent self, StartConfig allConfig, long id)
+        {
+            self.Awake(allConfig, id);
+        }
+    }
+
+    public class StartConfigComponent: Entity
+    {
+        public static StartConfigComponent Instance { get; private set; }
+
+        // 所有进程的配置
+        public StartConfig AllConfig;
+
+        // 当前进程的配置
+        public StartConfig StartConfig;
+        
+        // 所有domain的字典
+        private Dictionary<long, StartConfig> configDict = new Dictionary<long, StartConfig>();
+
+        // 所有有内网地址的进程字典
+        private Dictionary<long, string> innerAddressDict = new Dictionary<long, string>();
+        
+        // 所有agent
+        public Dictionary<long, StartConfig> Agents = new Dictionary<long, StartConfig>();
+        
+        private Dictionary<string, StartConfig> nameDict = new Dictionary<string, StartConfig>();
+        
+        private Dictionary<int, StartConfig> typeDict = new Dictionary<int, StartConfig>();
+
+        public List<StartConfig> Gates { get; } =  new List<StartConfig>();
+        
+        public void Awake(StartConfig allConfig, long id)
+        {
+            Instance = this;
+            this.AllConfig = allConfig;
+            this.AllConfig.Parent = this;
+
+            // 每个进程的配置
+            foreach (StartConfig s in this.AllConfig.List)
+            {
+                s.SceneInstanceId = (s.Id << IdGenerater.HeadPos) + s.Id;
+
+                if (s.Id == id)
+                {
+                    this.StartConfig = s;
+                }
+                
+                InnerConfig innerConfig = s.GetComponent<InnerConfig>();
+                if (innerConfig != null)
+                {
+                    this.innerAddressDict.Add(s.Id, innerConfig.Address);
+                }
+                
+                // 每个进程里面domain的配置
+                foreach (StartConfig startConfig in s.List)
+                {
+                    startConfig.SceneInstanceId = (startConfig.Parent.Id << IdGenerater.HeadPos) + startConfig.Id;
+                    
+                    this.configDict.Add(startConfig.Id, startConfig);
+
+                    SceneConfig sceneConfig = startConfig.GetComponent<SceneConfig>();
+
+                    switch (sceneConfig.SceneType)
+                    {
+                        case SceneType.Gate:
+                            this.Gates.Add(startConfig);
+                            break;
+                        case SceneType.Map:
+                            this.nameDict.Add(sceneConfig.Name, startConfig);
+                            break;
+                        default:
+                            this.typeDict.Add((int)sceneConfig.SceneType, startConfig);
+                            break;
+                    }
+                }
+            }
+        }
+        
+        public long GetInstanceId(SceneType sceneType)
+        {
+            if (!this.typeDict.TryGetValue((int) sceneType, out StartConfig startConfig))
+            {
+                throw new Exception($"GetInstanceId cant get StartConfig: {sceneType}");
+            }
+            return startConfig.SceneInstanceId;
+        }
+        
+        public StartConfig GetByType(SceneType sceneType)
+        {
+            if (!this.typeDict.TryGetValue((int) sceneType, out StartConfig startConfig))
+            {
+                throw new Exception($"GetByType cant get StartConfig: {sceneType}");
+            }
+            return startConfig;
+        }
+
+        public StartConfig GetByName(string sceneName)
+        {
+            if (!this.nameDict.TryGetValue(sceneName, out StartConfig startConfig))
+            {
+                throw new Exception($"GetByName cant get StartConfig: {sceneName}");
+            }
+            return startConfig;
+        }
+
+        public override void Dispose()
+        {
+            if (this.IsDisposed)
+            {
+                return;
+            }
+
+            base.Dispose();
+
+            Instance = null;
+            
+            this.configDict.Clear();
+            this.innerAddressDict.Clear();
+            this.Gates.Clear();
+            this.Agents.Clear();
+            this.typeDict.Clear();
+            this.nameDict.Clear();
+            this.StartConfig = null;
+        }
+
+        public StartConfig GetAgent(long agentId)
+        {
+            return this.Agents[agentId];
+        }
+
+        public StartConfig Get(long id)
+        {
+            try
+            {
+                return this.configDict[id];
+            }
+            catch (Exception e)
+            {
+                throw new Exception($"not found startconfig: {id}", e);
+            }
+        }
+        
+        public string GetProcessInnerAddress(long id)
+        {
+            try
+            {
+                // 内网地址需要找到进程配置,进程配置是domain配置的parent
+                return this.innerAddressDict[id];
+            }
+            catch (Exception e)
+            {
+                throw new Exception($"not found innerAddress: {id}", e);
+            }
+        }
+
+        public StartConfig[] GetAll()
+        {
+            List<StartConfig> startConfigs = new List<StartConfig>();
+            foreach (var kv in this.AllConfig.Children)
+            {
+                startConfigs.Add((StartConfig)kv.Value);
+            }
+            return startConfigs.ToArray();
+        }
+    }
+}

+ 5 - 16
Server/Model/Entity/Game.cs

@@ -2,20 +2,7 @@
 {
 	public static class Game
 	{
-		private static Scene scene;
-
-		public static Scene Scene
-		{
-			get
-			{
-				if (scene != null)
-				{
-					return scene;
-				}
-				scene = new Scene();
-				return scene;
-			}
-		}
+		public static Scene Scene { get; set; }
 
 		private static EventSystem eventSystem;
 
@@ -37,10 +24,12 @@
 			}
 		}
 
+		public static Options Options;
+
 		public static void Close()
 		{
-			scene.Dispose();
-			scene = null;
+			Scene.Dispose();
+			Scene = null;
 					
 			objectPool = null;
 			

+ 22 - 8
Server/Model/Entity/Scene.cs

@@ -2,24 +2,38 @@
 {
 	public sealed class Scene: Entity
 	{
+		public SceneType SceneType { get; set; }
+		
 		public string Name { get; set; }
 
-		public Scene()
+		public Scene Get(long id)
 		{
+			return (Scene)this.Children[id];
 		}
 
-		public Scene(long id): base(id)
+		public new Entity Domain
 		{
+			get
+			{
+				return this.domain;
+			}
+			set
+			{
+				this.domain = value;
+			}
 		}
-
-		public override void Dispose()
+		
+		public new Entity Parent
 		{
-			if (this.IsDisposed)
+			get
 			{
-				return;
+				return this.parent;
+			}
+			set
+			{
+				this.parent = value;
+				this.parent.Children.Add(this.Id, this);
 			}
-
-			base.Dispose();
 		}
 	}
 }

+ 3 - 12
Server/Model/Module/Actor/ActorMessageDispatcherComponent.cs

@@ -6,19 +6,10 @@ namespace ETModel
 	/// <summary>
 	/// Actor消息分发组件
 	/// </summary>
-	public class ActorMessageDispatcherComponent : Component
+	public class ActorMessageDispatcherComponent : Entity
 	{
+		public static ActorMessageDispatcherComponent Instance;
+		
 		public readonly Dictionary<Type, IMActorHandler> ActorMessageHandlers = new Dictionary<Type, IMActorHandler>();
-
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-			base.Dispose();
-
-			this.ActorMessageHandlers.Clear();
-		}
 	}
 }

+ 7 - 7
Server/Model/Module/Actor/ActorMessageSender.cs

@@ -1,19 +1,19 @@
-using System.Net;
+using System;
 
 namespace ETModel
 {
 	// 知道对方的instanceId,使用这个类发actor消息
 	public struct ActorMessageSender
 	{
+		// 最近接收或者发送消息的时间
+		public long CreateTime { get; }
 		// actor的地址
-		public IPEndPoint Address { get; }
+		public Action<IActorResponse> Callback { get; }
 
-		public long ActorId { get; }
-
-		public ActorMessageSender(long actorId, IPEndPoint address)
+		public ActorMessageSender(Action<IActorResponse> callback)
 		{
-			this.ActorId = actorId;
-			this.Address = address;
+			this.CreateTime = TimeHelper.Now();
+			this.Callback = callback;
 		}
 	}
 }

+ 13 - 13
Server/Model/Module/Actor/ActorMessageSenderComponent.cs

@@ -1,19 +1,19 @@
-using System;
-using System.Net;
+using System.Collections.Generic;
 
 namespace ETModel
 {
-	public class ActorMessageSenderComponent: Component
+	public class ActorMessageSenderComponent: Entity
 	{
-		public ActorMessageSender Get(long actorId)
-		{
-			if (actorId == 0)
-			{
-				throw new Exception($"actor id is 0");
-			}
-			IPEndPoint ipEndPoint = StartConfigComponent.Instance.GetInnerAddress(IdGenerater.GetAppId(actorId));
-			ActorMessageSender actorMessageSender = new ActorMessageSender(actorId, ipEndPoint);
-			return actorMessageSender;
-		}
+		public static long TIMEOUT_TIME = 30 * 1000;
+		
+		public static ActorMessageSenderComponent Instance { get; set; }
+		
+		public int RpcId;
+		
+		public readonly Dictionary<int, ActorMessageSender> requestCallback = new Dictionary<int, ActorMessageSender>();
+
+		public long TimeoutCheckTimer;
+		
+		public List<int> TimeoutActorMessageSenders = new List<int>();
 	}
 }

+ 3 - 21
Server/Model/Module/Actor/MailBoxComponent.cs

@@ -1,29 +1,11 @@
-using System.Collections.Generic;
-
-namespace ETModel
+namespace ETModel
 {
-	public struct ActorMessageInfo
-	{
-		public Session Session;
-		public object Message;
-	}
-
 	/// <summary>
 	/// 挂上这个组件表示该Entity是一个Actor,接收的消息将会队列处理
 	/// </summary>
-	public class MailBoxComponent: Component
+	public class MailBoxComponent: Entity
 	{
 		// Mailbox的类型
-		public string MailboxType;
-
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-
-			base.Dispose();
-		}
+		public MailboxType MailboxType;
 	}
 }

+ 4 - 13
Server/Model/Module/Actor/MailboxDispatcherComponent.cs

@@ -5,19 +5,10 @@ namespace ETModel
 	/// <summary>
 	/// mailbox分发组件,不同类型的mailbox交给不同的MailboxHandle处理
 	/// </summary>
-	public class MailboxDispatcherComponent : Component
+	public class MailboxDispatcherComponent : Entity
 	{
-		public readonly Dictionary<string, IMailboxHandler> MailboxHandlers = new Dictionary<string, IMailboxHandler>();
-
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-			base.Dispose();
-
-			this.MailboxHandlers.Clear();
-		}
+		public static MailboxDispatcherComponent Instance { get; set; }
+		
+		public readonly Dictionary<int, IMailboxHandler> MailboxHandlers = new Dictionary<int, IMailboxHandler>();
 	}
 }

+ 2 - 5
Server/Model/Module/Actor/MailboxHandlerAttribute.cs

@@ -2,13 +2,10 @@
 {
 	public class MailboxHandlerAttribute : BaseAttribute
 	{
-		public AppType Type { get; }
+		public MailboxType MailboxType { get; }
 
-		public string MailboxType { get; }
-
-		public MailboxHandlerAttribute(AppType appType, string mailboxType)
+		public MailboxHandlerAttribute(MailboxType mailboxType)
 		{
-			this.Type = appType;
 			this.MailboxType = mailboxType;
 		}
 	}

+ 6 - 5
Server/Model/Module/Actor/MailboxType.cs

@@ -1,8 +1,9 @@
 namespace ETModel
 {
-    public static partial class MailboxType
-    {
-	    public const string MessageDispatcher = "Dispatcher";
-		public const string GateSession = "GateSession";
-    }
+	public enum MailboxType
+	{
+		MessageDispatcher,
+		UnOrderMessageDispatcher,
+		GateSession,
+	}
 }

+ 11 - 24
Server/Model/Module/ActorLocation/ActorLocationSender.cs

@@ -1,28 +1,15 @@
-using System.Collections.Generic;
-using System.Net;
-
-namespace ETModel
+namespace ETModel
 {
-	// 知道对方的Id,使用这个类发actor消息
-	public class ActorLocationSender : ComponentWithId
-	{
-		public long ActorId;
-		
-		// 最近接收消息的时间
-		public long LastRecvTime;
-		
-		public int FailTimes;
+    // 知道对方的Id,使用这个类发actor消息
+    public class ActorLocationSender : Entity
+    {
+        public long ActorId;
 
-		public const int MaxFailTimes = 5;
+        // 最近接收或者发送消息的时间
+        public long LastSendOrRecvTime;
+		
+        public int FailTimes;
 
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-			
-			base.Dispose();
-		}
-	}
+        public const int MaxFailTimes = 5;
+    }
 }

+ 9 - 48
Server/Model/Module/ActorLocation/ActorLocationSenderComponent.cs

@@ -1,53 +1,14 @@
 using System;
-using System.Collections.Generic;
 
 namespace ETModel
 {
-	public class ActorLocationSenderComponent: Component
-	{
-		public readonly Dictionary<long, ActorLocationSender> ActorLocationSenders = new Dictionary<long, ActorLocationSender>();
+    public class ActorLocationSenderComponent: Entity
+    {
+        [NoMemoryCheck]
+        public static long TIMEOUT_TIME = 10 * 1000;
+        
+        public static ActorLocationSenderComponent Instance { get; set; }
 
-		public override void Dispose()
-		{
-			if (this.IsDisposed)
-			{
-				return;
-			}
-			
-			base.Dispose();
-			
-			foreach (ActorLocationSender actorLocationSender in this.ActorLocationSenders.Values)
-			{
-				actorLocationSender.Dispose();
-			}
-			this.ActorLocationSenders.Clear();
-		}
-
-		public ActorLocationSender Get(long id)
-		{
-			if (id == 0)
-			{
-				throw new Exception($"actor id is 0");
-			}
-			if (this.ActorLocationSenders.TryGetValue(id, out ActorLocationSender actorLocationSender))
-			{
-				return actorLocationSender;
-			}
-			
-			actorLocationSender = ComponentFactory.CreateWithId<ActorLocationSender>(id);
-			actorLocationSender.Parent = this;
-			this.ActorLocationSenders[id] = actorLocationSender;
-			return actorLocationSender;
-		}
-		
-		public void Remove(long id)
-		{
-			if (!this.ActorLocationSenders.TryGetValue(id, out ActorLocationSender actorMessageSender))
-			{
-				return;
-			}
-			this.ActorLocationSenders.Remove(id);
-			actorMessageSender.Dispose();
-		}
-	}
-}
+        public long CheckTimer;
+    }
+}

+ 0 - 12
Server/Model/Module/ActorLocation/Location.cs

@@ -1,12 +0,0 @@
-namespace ETModel
-{
-	public class Location: Entity
-	{
-		public string Address;
-
-		public Location(long id, string address): base(id)
-		{
-			this.Address = address;
-		}
-	}
-}

+ 55 - 55
Server/Model/Module/ActorLocation/LocationComponent.cs

@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
 
 namespace ETModel
 {
@@ -7,30 +8,17 @@ namespace ETModel
 	{
 		public override void Awake(LockInfo self, long lockInstanceId, CoroutineLock coroutineLock)
 		{
-			self.LockInstanceId = lockInstanceId;
 			self.CoroutineLock = coroutineLock;
+			self.LockInstanceId = lockInstanceId;
 		}
 	}
 	
-	public class LockInfo: Component
+	public class LockInfo: Entity
 	{
 		public long LockInstanceId;
 		
 		public CoroutineLock CoroutineLock;
 
-		public override void Dispose()
-		{
-			this.LockInstanceId = 0;
-			this.CoroutineLock.Dispose();
-		}
-	}
-	
-	public class LocationComponent : Component
-	{
-		private readonly Dictionary<long, long> locations = new Dictionary<long, long>();
-
-		private readonly Dictionary<long, LockInfo> lockInfos = new Dictionary<long, LockInfo>();
-		
 		public override void Dispose()
 		{
 			if (this.IsDisposed)
@@ -40,19 +28,21 @@ namespace ETModel
 			
 			base.Dispose();
 			
-			this.locations.Clear();
-
-			foreach (LockInfo lockInfo in this.lockInfos.Values)
-			{
-				lockInfo.Dispose();
-			}
-			
-			this.lockInfos.Clear();
+			this.CoroutineLock.Dispose();
+			this.CoroutineLock = null;
+			LockInstanceId = 0;
 		}
+	}
+	
+	public class LocationComponent : Entity
+	{
+		private readonly Dictionary<long, long> locations = new Dictionary<long, long>();
+		
+		private readonly Dictionary<long, LockInfo> lockInfos = new Dictionary<long, LockInfo>();
 
 		public async ETTask Add(long key, long instanceId)
 		{
-			using (await CoroutineLockComponent.Instance.Wait(key + (int)AppType.Location))
+			using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Location, key))
 			{
 				this.locations[key] = instanceId;
 				Log.Info($"location add key: {key} instanceId: {instanceId}");
@@ -61,69 +51,79 @@ namespace ETModel
 
 		public async ETTask Remove(long key)
 		{
-			using (await CoroutineLockComponent.Instance.Wait(key + (int)AppType.Location))
+			using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Location, key))
 			{
 				this.locations.Remove(key);
 				Log.Info($"location remove key: {key}");
 			}
 		}
 
-		public async ETTask<long> Get(long key)
+		public async ETVoid Lock(long key, long instanceId, int time = 0)
 		{
-			using (await CoroutineLockComponent.Instance.Wait(key + (int)AppType.Location))
+			CoroutineLock coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Location, key);
+
+			LockInfo lockInfo = EntityFactory.Create<LockInfo, long, CoroutineLock>(this.Domain, instanceId, coroutineLock);
+			lockInfo.Parent = this;
+			this.lockInfos.Add(key, lockInfo);
+			
+			Log.Info($"location lock key: {key} instanceId: {instanceId}");
+
+			if (time > 0)
 			{
-				this.locations.TryGetValue(key, out long instanceId);
-				Log.Info($"location get key: {key} {instanceId}");
-				return instanceId;
+				long lockInfoInstanceId = lockInfo.InstanceId;
+				await TimerComponent.Instance.WaitAsync(time);
+				if (lockInfo.InstanceId != lockInfoInstanceId)
+				{
+					return;
+				}
+				UnLock(key, instanceId, instanceId);
 			}
-
 		}
 
-		public async ETVoid Lock(long key, long instanceId, int time = 0)
+		public void UnLock(long key, long oldInstanceId, long newInstanceId)
 		{
-			if (!this.locations.TryGetValue(key, out long saveInstanceId))
+			if (!this.lockInfos.TryGetValue(key, out LockInfo lockInfo))
 			{
-				Log.Error($"actor没有注册, key: {key} InstanceId: {instanceId}");
+				Log.Error($"location unlock not found key: {key} {oldInstanceId}");
 				return;
 			}
 			
-			if (saveInstanceId != instanceId)
+			if (oldInstanceId != lockInfo.LockInstanceId)
 			{
-				Log.Error($"actor注册的instanceId与lock的不一致, key: {key} InstanceId: {instanceId} saveInstanceId: {saveInstanceId}");
+				Log.Error($"location unlock oldInstanceId is different: {key} {oldInstanceId}");
 				return;
 			}
 			
-			CoroutineLock coroutineLock = await CoroutineLockComponent.Instance.Wait(key + (int)AppType.Location);
+			Log.Info($"location unlock key: {key} instanceId: {oldInstanceId} newInstanceId: {newInstanceId}");
 
-			LockInfo lockInfo = ComponentFactory.Create<LockInfo, long, CoroutineLock>(instanceId, coroutineLock);
+			this.locations[key] = newInstanceId;
 			
-			this.lockInfos.Add(key, lockInfo);
+			this.lockInfos.Remove(key);
 			
-			Log.Info($"location lock key: {key} InstanceId: {instanceId}");
+			// 解锁
+			lockInfo.Dispose();
+		}
 
-			// 超时则解锁
-			if (time > 0)
+		public async ETTask<long> Get(long key)
+		{
+			using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Location, key))
 			{
-				await Game.Scene.GetComponent<TimerComponent>().WaitAsync(time);
-				this.UnLock(key, instanceId, instanceId);
+				this.locations.TryGetValue(key, out long instanceId);
+				Log.Info($"location get key: {key} instanceId: {instanceId}");
+				return instanceId;
 			}
 		}
 
-		public void UnLock(long key, long oldInstanceId, long newInstanceId)
+		public override void Dispose()
 		{
-			if (!this.lockInfos.TryGetValue(key, out LockInfo lockInfo))
-			{
-				return;
-			}
-			if (lockInfo.LockInstanceId != oldInstanceId)
+			if (this.IsDisposed)
 			{
-				Log.Error($"unlock appid is different {lockInfo.LockInstanceId} {oldInstanceId}" );
 				return;
 			}
-			Log.Info($"location unlock key: {key} oldInstanceId: {oldInstanceId} new: {newInstanceId}");
+			base.Dispose();
 			
-			this.locations[key] = newInstanceId;
-			lockInfo.Dispose();
+			this.locations.Clear();
+			this.lockInfos.Clear();
 		}
 	}
 }

+ 14 - 2
Server/Model/Module/ActorLocation/LocationProxyComponent.cs

@@ -2,8 +2,20 @@
 
 namespace ETModel
 {
-	public class LocationProxyComponent : Component
+	public class LocationProxyComponent : Entity
 	{
-		public IPEndPoint LocationAddress;
+		public static LocationProxyComponent Instance;
+
+		public override void Dispose()
+		{
+			if (this.IsDisposed)
+			{
+				return;
+			}
+			
+			base.Dispose();
+
+			Instance = null;
+		}
 	}
 }

+ 1 - 1
Server/Model/Module/Benchmark/BenchmarkComponent.cs

@@ -1,6 +1,6 @@
 namespace ETModel
 {
-	public class BenchmarkComponent: Component
+	public class BenchmarkComponent: Entity
 	{
 		public int k;
 

+ 1 - 1
Server/Model/Module/Benchmark/WebSocketBenchmarkComponent.cs

@@ -1,6 +1,6 @@
 namespace ETModel
 {
-	public class WebSocketBenchmarkComponent: Component
+	public class WebSocketBenchmarkComponent: Entity
 	{
 		public int k;
 

+ 1 - 1
Server/Model/Module/Config/ConfigComponent.cs

@@ -6,7 +6,7 @@ namespace ETModel
 	/// <summary>
 	/// Config组件会扫描所有的有ConfigAttribute标签的配置,加载进来
 	/// </summary>
-	public class ConfigComponent: Component
+	public class ConfigComponent: Entity
 	{
 		public Dictionary<Type, ACategory> AllConfig = new Dictionary<Type, ACategory>();
 	}

+ 14 - 78
Server/Model/Module/DB/DBComponent.cs

@@ -1,95 +1,31 @@
-using System.Collections.Generic;
+using System.Collections.Generic;
+using System.Text;
 using MongoDB.Driver;
 
 namespace ETModel
 {
-	[ObjectSystem]
-	public class DbComponentSystem : AwakeSystem<DBComponent>
-	{
-		public override void Awake(DBComponent self)
-		{
-			self.Awake();
-		}
-	}
-
 	/// <summary>
 	/// 用来缓存数据
 	/// </summary>
-	public class DBComponent : Component
+	public class DBComponent : Entity
 	{
+		public static DBComponent Instance;
+		
+		public List<string> Transfers = new List<string>();
+		
+		public const int TaskCount = 32;
+		
 		public MongoClient mongoClient;
 		public IMongoDatabase database;
 		
-		public const int taskCount = 32;
-		public List<DBTaskQueue> tasks = new List<DBTaskQueue>(taskCount);
-
-		public void Awake()
-		{
-			DBConfig config = StartConfigComponent.Instance.StartConfig.GetComponent<DBConfig>();
-			string connectionString = config.ConnectionString;
-			mongoClient = new MongoClient(connectionString);
-			this.database = this.mongoClient.GetDatabase(config.DBName);
-			
-			for (int i = 0; i < taskCount; ++i)
-			{
-				DBTaskQueue taskQueue = ComponentFactory.Create<DBTaskQueue>();
-				this.tasks.Add(taskQueue);
-			}
-		}
-		
-		public IMongoCollection<ComponentWithId> GetCollection(string name)
-		{
-			return this.database.GetCollection<ComponentWithId>(name);
-		}
-
-		public ETTask Add(ComponentWithId component, string collectionName = "")
+		public IMongoCollection<T> GetCollection<T>(string collection=null)
 		{
-			ETTaskCompletionSource tcs = new ETTaskCompletionSource();
-
-			if (string.IsNullOrEmpty(collectionName))
-			{
-				collectionName = component.GetType().Name;
-			}
-			DBSaveTask task = ComponentFactory.CreateWithId<DBSaveTask, ComponentWithId, string, ETTaskCompletionSource>(component.Id, component, collectionName, tcs);
-			this.tasks[(int)((ulong)task.Id % taskCount)].Add(task);
-
-			return tcs.Task;
-		}
-
-		public ETTask AddBatch(List<ComponentWithId> components, string collectionName)
-		{
-			ETTaskCompletionSource tcs = new ETTaskCompletionSource();
-			DBSaveBatchTask task = ComponentFactory.Create<DBSaveBatchTask, List<ComponentWithId>, string, ETTaskCompletionSource>(components, collectionName, tcs);
-			this.tasks[(int)((ulong)task.Id % taskCount)].Add(task);
-			return tcs.Task;
-		}
-
-		public ETTask<ComponentWithId> Get(string collectionName, long id)
-		{
-			ETTaskCompletionSource<ComponentWithId> tcs = new ETTaskCompletionSource<ComponentWithId>();
-			DBQueryTask dbQueryTask = ComponentFactory.CreateWithId<DBQueryTask, string, ETTaskCompletionSource<ComponentWithId>>(id, collectionName, tcs);
-			this.tasks[(int)((ulong)id % taskCount)].Add(dbQueryTask);
-
-			return tcs.Task;
-		}
-
-		public ETTask<List<ComponentWithId>> GetBatch(string collectionName, List<long> idList)
-		{
-			ETTaskCompletionSource<List<ComponentWithId>> tcs = new ETTaskCompletionSource<List<ComponentWithId>>();
-			DBQueryBatchTask dbQueryBatchTask = ComponentFactory.Create<DBQueryBatchTask, List<long>, string, ETTaskCompletionSource<List<ComponentWithId>>>(idList, collectionName, tcs);
-			this.tasks[(int)((ulong)dbQueryBatchTask.Id % taskCount)].Add(dbQueryBatchTask);
-
-			return tcs.Task;
-		}
+			return this.database.GetCollection<T>(collection ?? typeof (T).Name);
+		} 
 		
-		public ETTask<List<ComponentWithId>> GetJson(string collectionName, string json)
+		public IMongoCollection<Entity> GetCollection(string name)
 		{
-			ETTaskCompletionSource<List<ComponentWithId>> tcs = new ETTaskCompletionSource<List<ComponentWithId>>();
-			
-			DBQueryJsonTask dbQueryJsonTask = ComponentFactory.Create<DBQueryJsonTask, string, string, ETTaskCompletionSource<List<ComponentWithId>>>(collectionName, json, tcs);
-			this.tasks[(int)((ulong)dbQueryJsonTask.Id % taskCount)].Add(dbQueryJsonTask);
-
-			return tcs.Task;
+			return this.database.GetCollection<Entity>(name);
 		}
 	}
 }

+ 0 - 14
Server/Model/Module/DB/DBProxyComponent.cs

@@ -1,14 +0,0 @@
-using System.Net;
-
-namespace ETModel
-{
-	/// <summary>
-	/// 用来与数据库操作代理
-	/// </summary>
-	public class DBProxyComponent: Component
-	{
-		public IPEndPoint dbAddress;
-		
-		public MultiMap<string, object> TcsQueue = new MultiMap<string, object>();
-	}
-}

+ 0 - 54
Server/Model/Module/DB/DBQueryBatchTask.cs

@@ -1,54 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MongoDB.Driver;
-
-namespace ETModel
-{
-	[ObjectSystem]
-	public class DbQueryBatchTaskSystem : AwakeSystem<DBQueryBatchTask, List<long>, string, ETTaskCompletionSource<List<ComponentWithId>>>
-	{
-		public override void Awake(DBQueryBatchTask self, List<long> idList, string collectionName, ETTaskCompletionSource<List<ComponentWithId>> tcs)
-		{
-			self.IdList = idList;
-			self.CollectionName = collectionName;
-			self.Tcs = tcs;
-		}
-	}
-
-	public sealed class DBQueryBatchTask : DBTask
-	{
-		public string CollectionName { get; set; }
-
-		public List<long> IdList { get; set; }
-
-		public ETTaskCompletionSource<List<ComponentWithId>> Tcs { get; set; }
-		
-		public override async ETTask Run()
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-			List<ComponentWithId> result = new List<ComponentWithId>();
-
-			try
-			{
-				// 执行查询数据库任务
-				foreach (long id in IdList)
-				{
-					IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == id);
-					ComponentWithId component = await cursor.FirstOrDefaultAsync();
-					
-					if (component == null)
-					{
-						continue;
-					}
-					result.Add(component);
-				}
-				
-				this.Tcs.SetResult(result);
-			}
-			catch (Exception e)
-			{
-				this.Tcs.SetException(new Exception($"查询数据库异常! {this.CollectionName} {IdList.ListToString()}", e));
-			}
-		}
-	}
-}

+ 0 - 43
Server/Model/Module/DB/DBQueryJsonTask.cs

@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MongoDB.Driver;
-
-namespace ETModel
-{
-	[ObjectSystem]
-	public class DBQueryJsonTaskAwakeSystem : AwakeSystem<DBQueryJsonTask, string, string, ETTaskCompletionSource<List<ComponentWithId>>>
-	{
-		public override void Awake(DBQueryJsonTask self, string collectionName, string json, ETTaskCompletionSource<List<ComponentWithId>> tcs)
-		{
-			self.CollectionName = collectionName;
-			self.Json = json;
-			self.Tcs = tcs;
-		}
-	}
-
-	public sealed class DBQueryJsonTask : DBTask
-	{
-		public string CollectionName { get; set; }
-
-		public string Json { get; set; }
-
-		public ETTaskCompletionSource<List<ComponentWithId>> Tcs { get; set; }
-		
-		public override async ETTask Run()
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-			try
-			{
-				// 执行查询数据库任务
-				FilterDefinition<ComponentWithId> filterDefinition = new JsonFilterDefinition<ComponentWithId>(this.Json);
-				IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync(filterDefinition);
-				List<ComponentWithId> components = await cursor.ToListAsync();
-				this.Tcs.SetResult(components);
-			}
-			catch (Exception e)
-			{
-				this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {this.Json}", e));
-			}
-		}
-	}
-}

+ 0 - 38
Server/Model/Module/DB/DBQueryTask.cs

@@ -1,38 +0,0 @@
-using System;
-using MongoDB.Driver;
-
-namespace ETModel
-{
-	[ObjectSystem]
-	public class DBQueryTaskSystem : AwakeSystem<DBQueryTask, string, ETTaskCompletionSource<ComponentWithId>>
-	{
-		public override void Awake(DBQueryTask self, string collectionName, ETTaskCompletionSource<ComponentWithId> tcs)
-		{
-			self.CollectionName = collectionName;
-			self.Tcs = tcs;
-		}
-	}
-
-	public sealed class DBQueryTask : DBTask
-	{
-		public string CollectionName { get; set; }
-
-		public ETTaskCompletionSource<ComponentWithId> Tcs { get; set; }
-
-		public override async ETTask Run()
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-			try
-			{
-				// 执行查询数据库任务
-				IAsyncCursor<ComponentWithId> cursor = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == this.Id);
-				ComponentWithId component = await cursor.FirstOrDefaultAsync();
-				this.Tcs.SetResult(component);
-			}
-			catch (Exception e)
-			{
-				this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {Id}", e));
-			}
-		}
-	}
-}

+ 0 - 52
Server/Model/Module/DB/DBSaveBatchTask.cs

@@ -1,52 +0,0 @@
-using System;
-using System.Collections.Generic;
-using MongoDB.Bson;
-using MongoDB.Driver;
-
-namespace ETModel
-{
-	[ObjectSystem]
-	public class DbSaveBatchTaskSystem : AwakeSystem<DBSaveBatchTask, List<ComponentWithId>, string, ETTaskCompletionSource>
-	{
-		public override void Awake(DBSaveBatchTask self, List<ComponentWithId> components, string collectionName, ETTaskCompletionSource tcs)
-		{
-			self.Components = components;
-			self.CollectionName = collectionName;
-			self.Tcs = tcs;
-		}
-	}
-
-	public sealed class DBSaveBatchTask : DBTask
-	{
-		public string CollectionName { get; set; }
-
-		public List<ComponentWithId> Components;
-
-		public ETTaskCompletionSource Tcs;
-	
-		public override async ETTask Run()
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-
-			foreach (ComponentWithId component in this.Components)
-			{
-				if (component == null)
-				{
-					continue;
-				}
-
-				try
-				{
-					// 执行保存数据库任务
-					await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == component.Id, component, new UpdateOptions { IsUpsert = true });
-				}
-				catch (Exception e)
-				{
-					Log.Debug($"{component.GetType().Name} {component.ToJson()} {e}");
-					this.Tcs.SetException(new Exception($"保存数据失败! {CollectionName} {this.Components.ListToString()}", e));
-				}
-			}
-			this.Tcs.SetResult();
-		}
-	}
-}

+ 0 - 42
Server/Model/Module/DB/DBSaveTask.cs

@@ -1,42 +0,0 @@
-using System;
-using MongoDB.Driver;
-
-namespace ETModel
-{
-
-	[ObjectSystem]
-	public class DbSaveTaskAwakeSystem : AwakeSystem<DBSaveTask, ComponentWithId, string, ETTaskCompletionSource>
-	{
-		public override void Awake(DBSaveTask self, ComponentWithId component, string collectionName, ETTaskCompletionSource tcs)
-		{
-			self.Component = component;
-			self.CollectionName = collectionName;
-			self.Tcs = tcs;
-		}
-	}
-
-	public sealed class DBSaveTask : DBTask
-	{
-		public ComponentWithId Component;
-
-		public string CollectionName { get; set; }
-
-		public ETTaskCompletionSource Tcs;
-
-		public override async ETTask Run()
-		{
-			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
-
-			try
-			{
-				// 执行保存数据库任务
-				await dbComponent.GetCollection(this.CollectionName).ReplaceOneAsync(s => s.Id == this.Component.Id, this.Component, new UpdateOptions {IsUpsert = true});
-				this.Tcs.SetResult();
-			}
-			catch (Exception e)
-			{
-				this.Tcs.SetException(new Exception($"保存数据失败!  {CollectionName} {Id}", e));
-			}
-		}
-	}
-}

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно