Skip to content

Commit

Permalink
整合内嵌数据库和mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
leeveel committed Nov 23, 2022
1 parent 7cddc55 commit 8469d8e
Show file tree
Hide file tree
Showing 116 changed files with 2,301 additions and 544 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,4 @@ MigrationBackup/
/UnityDemo/Library
/UnityDemo/Temp
/.idea
/database
1 change: 1 addition & 0 deletions Geek.Server.App/Common/Session/SessionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Geek.Server.Core.Actors;
using Geek.Server.Core.Events;
using Geek.Server.Core.Net.Tcp.Codecs;
using Geek.Server.Proto;

namespace Geek.Server.App.Common.Session
{
Expand Down
8 changes: 5 additions & 3 deletions Geek.Server.App/Configs/app_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
"HttpCode": "inner_httpcode",
"HttpPort": 20000,
"GrpcPort": 30000,
"LocalDBPrefix": "gamedb_",
"LocalDBPath": "../../database/game/",
"SDKType": 0,
"DBModel": 0, //0:内嵌 1:mongodb
"MongoUrl": "mongodb://127.0.0.1:27017/?authSource=admin",
"DbName": "geek_server",
"Language": "chinese",
"SDKType": 0
"MongoDBName": "geek_server"
}
File renamed without changes.
8 changes: 4 additions & 4 deletions Geek.Server.App/Geek.Server.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<PropertyGroup>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<ApplicationIcon />
<StartupObject />
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand All @@ -19,10 +21,7 @@
</PropertyGroup>

<ItemGroup>
<None Update="Configs\NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Configs\NLog.xsd">
<None Update="Configs\app_log.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Configs\app_config.json">
Expand All @@ -32,6 +31,7 @@

<ItemGroup>
<ProjectReference Include="..\Geek.Server.Generate\Geek.Server.Generate.csproj" />
<ProjectReference Include="..\Geek.Server.CodeGenerator\Geek.Server.CodeGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

</Project>
12 changes: 10 additions & 2 deletions Geek.Server.App/Logic/Login/LoginComp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace Geek.Server.App.Logic.Login
{

public class PlayerInfo : InnerState
{
//player相对特殊,id不是long,所以不继承DBState,自定义mongoDB的id
Expand All @@ -20,9 +21,16 @@ public class PlayerInfo : InnerState
public bool IsChanged;
}

[Comp(ActorType.Server)]
public class LoginComp : BaseComp
public class LoginState : CacheState
{
public ConcurrentDictionary<string, PlayerInfo> PlayerMap = new();
}


[Comp(ActorType.Server)]
public class LoginComp : StateComp<LoginState>
{

}

}
1 change: 1 addition & 0 deletions Geek.Server.App/Logic/Role/Bag/BagComp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Geek.Server.App.Logic.Role.Bag
{

public class BagState : CacheState
{
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
Expand Down
5 changes: 2 additions & 3 deletions Geek.Server.App/Logic/Server/ServerComp.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@

using Geek.Server.Core.Actors;
using Geek.Server.Core.Actors;
using Geek.Server.Core.Comps;
using Geek.Server.Core.Storage;

namespace Geek.Server.App.Logic.Server
{

public class ServerState : CacheState
{
/// <summary>
Expand All @@ -16,6 +14,7 @@ public class ServerState : CacheState
public List<long> OnlineList { get; set; } = new List<long>();
}


[Comp(ActorType.Server)]
public class ServerComp : StateComp<ServerState>
{
Expand Down
8 changes: 7 additions & 1 deletion Geek.Server.App/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Geek.Server.App.Common;
using Geek.Server.Core.Comps;
using Geek.Server.Core.Hotfix;
using Geek.Server.Core.Storage;
using Geek.Server.Core.Utils;
using Geek.Server.Proto;
using NLog;
Expand All @@ -23,10 +24,12 @@ static async Task Main(string[] args)
Console.WriteLine($"init NLog config...");
Settings.Load<AppSetting>("Configs/app_config.json", ServerType.Game);
LayoutRenderer.Register<NLogConfigurationLayoutRender>("logConfiguration");
LogManager.Configuration = new XmlLoggingConfiguration("Configs/NLog.config");
LogManager.Configuration = new XmlLoggingConfiguration("Configs/app_log.config");
LogManager.AutoShutdown = false;

PolymorphicRegister.Load();
GeekServerAppPolymorphicDBStateRegister.Load();

GameLoopTask = EnterGameLoop();
await GameLoopTask;
if (ShutDownTask != null)
Expand Down Expand Up @@ -58,6 +61,9 @@ private static async Task EnterGameLoop()
{
try
{
Log.Info($"launch embedded db...");
GameDB.Init();
GameDB.Open();
Log.Info($"regist comps...");
await CompRegister.Init();
Log.Info($"load hotfix module");
Expand Down
3 changes: 1 addition & 2 deletions Geek.Server.App/Usings.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
global using MongoDB.Bson.Serialization.Attributes;
global using MongoDB.Bson.Serialization.Options;
global using Geek.Server.Proto;
global using MongoDB.Bson.Serialization.Options;
2 changes: 2 additions & 0 deletions Geek.Server.CodeGenerator/Geek.Server.CodeGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
</PropertyGroup>

<ItemGroup>
<None Remove="Template\PolymorphicDBStateRegister.liquid" />
<None Remove="Template\State.liquid" />
</ItemGroup>

Expand All @@ -36,6 +37,7 @@
<ItemGroup>
<EmbeddedResource Include="$(PKGScriban)\lib\netstandard2.0\Scriban.dll" Visible="false" />
<EmbeddedResource Include="$(ProjectPath)\..\Template\Agent.liquid" Visible="true" />
<EmbeddedResource Include="Template\PolymorphicDBStateRegister.liquid" />
</ItemGroup>

</Project>
67 changes: 67 additions & 0 deletions Geek.Server.CodeGenerator/State/DBStateFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Geek.Server.CodeGenerator.State
{
public class DBStateFilter : ISyntaxReceiver
{
public const string NESTED_CLASS_DELIMITER = ".";
public const string NAMESPACE_CLASS_DELIMITER = ".";

public Dictionary<string, string> classFullNamePair = new Dictionary<string, string>();
public Dictionary<string, List<string>> classPair = new Dictionary<string, List<string>>();

public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax source)
{
if (source.BaseList == null)
return;
var baseTypes = source.BaseList.Types.ToArray();
var list = new List<string>();

var className = source.Identifier.Text;
classFullNamePair[className] = GetFullName(source);
classPair[source.Identifier.Text] = list;
foreach (var v in baseTypes)
{
list.Add(v.ToString());
}
}
}

public static string GetFullName(ClassDeclarationSyntax source)
{
var items = new List<string>();
var parent = source.Parent;
while (parent.IsKind(SyntaxKind.ClassDeclaration))
{
var parentClass = parent as ClassDeclarationSyntax;
if (parentClass == null)
{
break;
}
items.Add(parentClass.Identifier.Text);

parent = parent.Parent;
}

var nameSpace = parent as NamespaceDeclarationSyntax;

var sb = new StringBuilder();
if (nameSpace != null)
sb.Append(nameSpace.Name);
sb.Append(NAMESPACE_CLASS_DELIMITER);
items.Reverse();
items.ForEach(i => { sb.Append(i).Append(NESTED_CLASS_DELIMITER); });
sb.Append(source.Identifier.Text);

var result = sb.ToString();
return result;
}
}
}
151 changes: 151 additions & 0 deletions Geek.Server.CodeGenerator/State/MessagePackRegisterGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using System.Collections.Generic;
using Geek.Server.CodeGenerator.Utils;
using Microsoft.CodeAnalysis;
using Scriban;

namespace Geek.Server.CodeGenerator.State
{
[Generator]
public class MessagePackRegisterGenerator : ISourceGenerator
{
const string baseDBStateName = "InnerState";
const string dBStateName = "CacheState";
public void Initialize(GeneratorInitializationContext context)
{
//Debugger.Launch();
ResLoader.LoadDll();
context.RegisterForSyntaxNotifications(() => new DBStateFilter());
}

public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is DBStateFilter receiver)
{
var str = ResLoader.LoadTemplate("PolymorphicDBStateRegister.liquid");
Template agentTemplate = Template.Parse(str);

var inheritDBBaseMap = new Dictionary<string, string>();
foreach (var v in receiver.classFullNamePair)
{
var c = GetInheritDBBase(receiver.classPair, v.Key, v.Key);
if (c != "")
{
inheritDBBaseMap[v.Key] = c;
}
}

var assemblyName = context.Compilation.AssemblyName;
if (assemblyName == null)
assemblyName = "";
var arr = new PolymorphicInfoArray();
arr.prefix = assemblyName.Replace(".", "");

foreach (var v in inheritDBBaseMap)
{
var keyFullName = GetFullName(receiver.classFullNamePair, v.Key);
AddInfo(arr, keyFullName, keyFullName);
AddGetAllSubClass(arr, receiver.classFullNamePair, inheritDBBaseMap, v.Key, v.Key);
}

RemoveFinalClass(arr, inheritDBBaseMap, receiver.classFullNamePair);

var source = agentTemplate.Render(arr);
//File.WriteAllText($"PolymorphicDBStateRegister.cs", source);
context.AddSource($"{arr.prefix}PolymorphicDBStateRegister.g.cs", source);
}
}

string GetInheritDBBase(Dictionary<string, List<string>> classPair, string startClassName, string currentClassName)
{
if (classPair.TryGetValue(currentClassName, out var list))
{
foreach (var l in list)
{
if (l == baseDBStateName)
{
return currentClassName == startClassName ? baseDBStateName : currentClassName;
}
if (l == dBStateName)
{
return currentClassName == startClassName ? dBStateName : currentClassName;
}
var str = GetInheritDBBase(classPair, startClassName, l);
if (str != "")
return str;
}
}
return "";
}

string GetFullName(Dictionary<string, string> nameMap, string name)
{
if (nameMap.TryGetValue(name, out var outName))
{
return outName;
}
if (name == baseDBStateName)
{
return "Geek.Server.Core.Storage.InnerState";
}
if (name == dBStateName)
{
return "Geek.Server.Core.Storage.CacheState";
}
return "";
}

void AddGetAllSubClass(PolymorphicInfoArray arr, Dictionary<string, string> fullNameMap, Dictionary<string, string> inheritDBBaseMap, string startClass, string curClass)
{
var baseName = GetFullName(fullNameMap, startClass);
while (true)
{
if (inheritDBBaseMap.TryGetValue(curClass, out var inher))
{
var subname = GetFullName(fullNameMap, inher);
if (arr.infos.Find(v => v.basename == baseName && v.subname == subname) != null)
{
return;
}
AddInfo(arr, baseName, subname);
if (inher == baseDBStateName || inher == dBStateName)
{
return;
}
AddGetAllSubClass(arr, fullNameMap, inheritDBBaseMap, startClass, inher);
}
}
}

void AddInfo(PolymorphicInfoArray arr, string baseName, string subName)
{
//if (baseName != subName)
arr.infos.Add(new PolymorphicInfo { basename = baseName, subname = subName, subsid = ((int)MurmurHash3.Hash(baseName, 27)).ToString() });
//arr.infos.Add(new PolymorphicInfo { basename = baseName, subname = subName, subsid = ((int)xxHash32.ComputeHash(nameBytes, 0, nameBytes.Length, 27)).ToString() });
}

void RemoveFinalClass(PolymorphicInfoArray arr, Dictionary<string, string> inheritDBBaseMap, Dictionary<string, string> classFullNamePair)
{
var all = arr.infos.ToArray();
foreach (var c in all)
{
if (c.basename == c.subname)
{
bool needRemove = true;
foreach (var kv in inheritDBBaseMap)
{
if (c.basename == GetFullName(classFullNamePair, kv.Value))
{
needRemove = false;
break;
}
}
if (needRemove)
{
arr.infos.Remove(c);
}
}
}
}
}

}
Loading

0 comments on commit 8469d8e

Please sign in to comment.