fix synapse use mqtt

This commit is contained in:
2024-07-26 05:03:28 +08:00
parent 56b0490d1e
commit f4bc6dc080
8 changed files with 221 additions and 249 deletions
+6 -12
View File
@@ -2,28 +2,22 @@ namespace SimApi.Configurations;
public class SimApiSynapseOptions public class SimApiSynapseOptions
{ {
public string MqHost { get; set; } /// <summary>
/// Mqtt服务器的Websocket地址
/// </summary>
public string Websocket { get; set; }
public int MqPort { get; set; } public string Username { get; set; }
public string MqUser { get; set; } public string Password { get; set; }
public string MqPass { get; set; }
public string MqVHost { get; set; } = "/";
public string SysName { get; set; } public string SysName { get; set; }
public string AppName { get; set; } public string AppName { get; set; }
public string AppId { get; set; } public string AppId { get; set; }
public int RpcTimeout { get; set; } = 3; public int RpcTimeout { get; set; } = 3;
public ushort EventProcessorNum { get; set; } = 20;
public ushort RpcProcessorNum { get; set; } = 20;
public bool DisableEventClient { get; set; } = false; public bool DisableEventClient { get; set; } = false;
public bool DisableRpcClient { get; set; } = false; public bool DisableRpcClient { get; set; } = false;
+1 -1
View File
@@ -26,7 +26,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Minio" Version="6.0.3" /> <PackageReference Include="Minio" Version="6.0.3" />
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" /> <PackageReference Include="MQTTnet" Version="4.3.6.1152" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.6.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.6.2" />
</ItemGroup> </ItemGroup>
+30
View File
@@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using SimApi.Middlewares; using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SimApi.Configurations; using SimApi.Configurations;
using SimApi.Logger; using SimApi.Logger;
@@ -189,6 +190,35 @@ public static class SimApiExtensions
return builder; return builder;
} }
public static IHost UseSimApi(this IHost builder)
{
var options = builder.Services.GetRequiredService<SimApiOptions>();
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
//请求一下检测存储错误
if (options.EnableSimApiStorage)
{
logger.LogInformation("开始配置SimApiStorage...");
builder.Services.GetService<SimApiStorage>();
}
if (options.EnableLowerUrl)
{
logger.LogInformation("开始配置使用URL小写...");
}
if (options.EnableSynapse)
{
var synapse = builder.Services.GetRequiredService<Synapse>();
synapse.Init();
}
return builder;
}
/// <summary> /// <summary>
/// 使用所有SimApi自定义中间件 /// 使用所有SimApi自定义中间件
/// </summary> /// </summary>
+13 -19
View File
@@ -1,31 +1,25 @@
using System;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Unicode; using System.Threading;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MQTTnet;
using SimApi.Helpers; using SimApi.Helpers;
namespace SimApi; namespace SimApi;
public partial class Synapse public partial class Synapse
{ {
private void RunEventClient() private bool FireEvent(string eventName, object param, bool retain = false)
{
EventClientChannel = CreateChannel(0, "EventClient");
}
private void FireEvent(string eventName, object param)
{ {
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption); var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
var router = $"event.{Options.AppName}.{eventName}"; var topic = $"{Options.SysName}/{Options.AppName}/event/{eventName}";
var props = EventClientChannel.CreateBasicProperties(); var message = new MqttApplicationMessageBuilder()
props.AppId = Options.AppId; .WithTopic(topic)
props.MessageId = Guid.NewGuid().ToString(); .WithPayload(paramJson)
props.ReplyTo = Options.AppName; .WithRetainFlag(retain)
props.Type = eventName; .Build();
EventClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson)); if (!Client!.IsConnected) return false;
Logger.LogDebug("Event Publish: {OptionsAppName}.{EventName}\n{ParamJson}", Options.AppName, eventName, Client!.PublishAsync(message, CancellationToken.None).Wait();
paramJson); logger.LogDebug("Event Publish: {Event}@{App} {Json}", eventName, Options.AppName, paramJson);
return true;
} }
} }
+22 -23
View File
@@ -1,10 +1,11 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events; using MQTTnet;
using MQTTnet.Protocol;
using SimApi.Helpers; using SimApi.Helpers;
namespace SimApi; namespace SimApi;
@@ -13,38 +14,36 @@ public partial class Synapse
{ {
private void RunEventServer() private void RunEventServer()
{ {
EventServerChannel = CreateChannel(Options.EventProcessorNum, "EventServer"); var esTopicPrefix = $"{Options.SysName}/{Options.AppName}/event/";
var queue = $"{Options.SysName}_{Options.AppName}_event"; var eventSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
EventServerChannel.QueueDeclare(queue, true, false, true, null); .WithTopicFilter(o =>
foreach (var ev in EventRegistry.Where(ev => !ev.Key.Contains('*') && !ev.Key.Contains('#'))) o.WithTopic($"$queue/{esTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
.Build();
Client.ApplicationMessageReceivedAsync += e =>
{ {
EventServerChannel.QueueBind(queue, Options.SysName, $"event.{ev.Key}", null); if (!e.ApplicationMessage.Topic.StartsWith(esTopicPrefix)) return Task.CompletedTask;
} var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var consumer = new EventingBasicConsumer(EventServerChannel); var eventName = e.ApplicationMessage.Topic.Replace(esTopicPrefix, string.Empty);
consumer.Received += (ch, ea) => logger.LogDebug("Synapse Event Receive: {AppName}.{EventName}\n{Body}",
{ Options.AppName, eventName, reqBody);
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
Logger.LogDebug("Event Receive: {BasicPropertiesReplyTo}.{BasicPropertiesType}\n{S}",
ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, reqBody);
var key = ea.RoutingKey.Replace("event.", string.Empty); var method = EventRegistry.FirstOrDefault(x => x.Key == eventName);
var method = EventRegistry.FirstOrDefault(x => x.Key == key); if (method == null) return Task.CompletedTask;
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class); var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method!.Class);
var mt = callClass.GetType().GetMethod(method.Method); var mt = callClass.GetType().GetMethod(method.Method);
var pt = mt.GetParameters()[0].ParameterType; var pt = mt!.GetParameters()[0].ParameterType;
try try
{ {
mt.Invoke(callClass, pt == typeof(string) mt.Invoke(callClass, pt == typeof(string)
? new object[] { reqBody } ? new object[] { reqBody }
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) }); : new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
EventServerChannel.BasicAck(ea.DeliveryTag, false);
} }
catch (Exception e) catch (Exception ex)
{ {
Logger.LogError("Event Processor Error: {Err}", e.InnerException); logger.LogError("SynapseEvent Processor Error: {Err}", ex.InnerException);
EventServerChannel.BasicNack(ea.DeliveryTag, false, false);
} }
return Task.CompletedTask;
}; };
EventServerChannel.BasicConsume(queue, false, "", false, false, null, consumer); Client.SubscribeAsync(eventSubOpts).Wait();
} }
} }
+38 -33
View File
@@ -1,9 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events; using MQTTnet;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Helpers; using SimApi.Helpers;
@@ -11,42 +12,43 @@ namespace SimApi;
public partial class Synapse public partial class Synapse
{ {
private Dictionary<string, byte[]> ResponseCache { get; } = new(); private Dictionary<string, string> ResponseCache { get; } = new();
private void RunRpcClient() private void RunRpcClient()
{ {
RpcClientChannel = CreateChannel(0, "RpcClient"); var rcTopic = $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
var queue = $"{Options.SysName}_{Options.AppName}_client_{Options.AppId}"; var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
var router = $"client.{Options.AppName}.{Options.AppId}"; .WithTopicFilter(o => o.WithTopic($"{rcTopic}+")).Build();
RpcClientChannel.QueueDeclare(queue, true, false, true, null); Client.ApplicationMessageReceivedAsync += e =>
RpcClientChannel.QueueBind(queue, Options.SysName, router, null);
var consumer = new EventingBasicConsumer(RpcClientChannel);
consumer.Received += (ch, ea) =>
{ {
ResponseCache.Add(ea.BasicProperties.CorrelationId, ea.Body.ToArray()); if (!e.ApplicationMessage.Topic.StartsWith(rcTopic)) return Task.CompletedTask;
RpcClientChannel.BasicAck(ea.DeliveryTag, false); var reqBody = e.ApplicationMessage.ConvertPayloadToString();
Logger.LogDebug( var messageId = e.ApplicationMessage.Topic.Replace(rcTopic, string.Empty);
"RPC Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}", ResponseCache.Add(messageId, reqBody);
ea.BasicProperties.CorrelationId, ea.BasicProperties.Type, ea.BasicProperties.ReplyTo, Options.AppName, logger.LogDebug("Synapse RPC Client Message: ({BasicPropertiesCorrelationId}) => {S}", messageId, reqBody);
Encoding.UTF8.GetString(ea.Body.ToArray())); return Task.CompletedTask;
}; };
RpcClientChannel.BasicConsume(queue, false, "", false, false, null, consumer); Client.SubscribeAsync(rcSubOpts).Wait();
} }
private string FireRpc(string app, string action, object param) private string FireRpc(string app, string action, object param)
{ {
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption); var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
var router = $"server.{app}";
string response; string response;
var props = RpcClientChannel.CreateBasicProperties(); var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
props.AppId = Options.AppId; var messageId = Guid.NewGuid().ToString();
props.MessageId = Guid.NewGuid().ToString(); var message = new MqttApplicationMessageBuilder()
props.Type = action; .WithTopic(topic)
props.ReplyTo = Options.AppName; .WithPayload(paramJson)
RpcClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson)); .WithResponseTopic($"{Options.AppName},{Options.AppId}")
Logger.LogDebug("RPC Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}", .WithContentType(messageId)
props.MessageId, .WithRetainFlag(false)
Options.AppName, action, app, paramJson); .Build();
if (!Client!.IsConnected) return null;
Client!.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug(
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}",
messageId, Options.AppName, action, app, paramJson);
var ts = SimApiUtil.TimestampNow; var ts = SimApiUtil.TimestampNow;
while (true) while (true)
{ {
@@ -55,13 +57,16 @@ public partial class Synapse
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption); response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
break; break;
} }
if (ResponseCache.TryGetValue(props.MessageId, out var value))
{ if (!ResponseCache.TryGetValue(messageId, out var value)) continue;
response = Encoding.UTF8.GetString(value); response = value;
ResponseCache.Remove(props.MessageId); ResponseCache.Remove(messageId);
break; logger.LogDebug(
} "Synapse RPC Client Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
messageId, action, app, Options.AppName, response);
break;
} }
return response; return response;
} }
} }
+58 -64
View File
@@ -1,10 +1,12 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events; using MQTTnet;
using MQTTnet.Protocol;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Exceptions; using SimApi.Exceptions;
using SimApi.Helpers; using SimApi.Helpers;
@@ -16,78 +18,70 @@ public partial class Synapse
{ {
private void RunRpcServer() private void RunRpcServer()
{ {
RpcServerChannel = CreateChannel(Options.RpcProcessorNum, "RpcServer"); var rsTopicPrefix = $"{Options.SysName}/{Options.AppName}/rpc/server/";
var queue = $"{Options.SysName}_{Options.AppName}_server"; var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
var router = $"server.{Options.AppName}"; .WithTopicFilter(o =>
RpcServerChannel.QueueDeclare(queue, true, false, true, null); o.WithTopic($"$queue/{rsTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
RpcServerChannel.QueueBind(queue, Options.SysName, router, null); .Build();
var consumer = new EventingBasicConsumer(RpcServerChannel); Client.ApplicationMessageReceivedAsync += e =>
consumer.Received += (ch, ea) =>
{ {
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray()); if (!e.ApplicationMessage.Topic.StartsWith(rsTopicPrefix)) return Task.CompletedTask;
Logger.LogDebug( var reqBody = e.ApplicationMessage.ConvertPayloadToString();
"RPC Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}", var action = e.ApplicationMessage.Topic.Replace(rsTopicPrefix, string.Empty);
ea.BasicProperties.MessageId, ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, Options.AppName, var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
logger.LogDebug(
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
e.ApplicationMessage.ContentType, appInfo[0], action, Options.AppName,
reqBody); reqBody);
var res = new SimApiBaseResponse(404, "method not found"); var res = new SimApiBaseResponse(404, "method not found");
var method = RpcRegistry.FirstOrDefault(x => x.Key == ea.BasicProperties.Type); var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
if (method != null) if (method == null) return Task.CompletedTask;
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
var mt = callClass.GetType().GetMethod(method.Method);
try
{ {
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class); var pt = mt!.GetParameters()[0].ParameterType;
var mt = callClass.GetType().GetMethod(method.Method); var param = pt == typeof(string)
var param = Array.Empty<object>(); ? [reqBody]
try : new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
var ret = mt.Invoke(callClass, param);
res = new SimApiBaseResponse<object>
{ {
var pt = mt.GetParameters()[0].ParameterType; Data = ret
if (pt == typeof(string)) };
{ }
param = new[] { reqBody }; catch (TargetInvocationException ex)
} {
else if (ex.InnerException is SimApiException ie)
{ {
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption); logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
param = new[] { paramObj }; res = new SimApiBaseResponse(ie.Code, ie.Message);
}
var ret = mt.Invoke(callClass, param);
res = new SimApiBaseResponse<object>
{
Data = ret
};
} }
catch (TargetInvocationException e) else
{ {
if (e.InnerException is SimApiException ie) res = new SimApiBaseResponse(500, ex.Message);
{
Logger.LogDebug("RPC调用错误: {Err}", ie.Message);
res = new SimApiBaseResponse(ie.Code, ie.Message);
}
else
{
res = new SimApiBaseResponse(500, e.Message);
}
}
catch (Exception e)
{
Logger.LogDebug("RPC调用失败: {Err}", e.Message);
res = new SimApiBaseResponse(500, e.Message);
} }
} }
catch (Exception ex)
{
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
res = new SimApiBaseResponse(500, ex.Message);
}
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption); var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
var reply = $"client.{ea.BasicProperties.ReplyTo}.{ea.BasicProperties.AppId}"; var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{e.ApplicationMessage.ContentType}";
var props = RpcServerChannel.CreateBasicProperties(); var message = new MqttApplicationMessageBuilder()
props.AppId = Options.AppId; .WithTopic(reply)
props.CorrelationId = ea.BasicProperties.MessageId; .WithPayload(returnJson)
props.MessageId = Guid.NewGuid().ToString(); .WithRetainFlag(false)
props.ReplyTo = Options.AppName; .Build();
props.Type = ea.BasicProperties.Type; if (!Client!.IsConnected) return Task.CompletedTask;
RpcServerChannel.BasicPublish(Options.SysName, reply, false, props, Encoding.UTF8.GetBytes(returnJson)); Client!.PublishAsync(message, CancellationToken.None).Wait();
Logger.LogDebug( logger.LogDebug(
"Rpc Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}", "Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
ea.BasicProperties.MessageId, ea.BasicProperties.Type, Options.AppName, ea.BasicProperties.ReplyTo, e.ApplicationMessage.ContentType, action, Options.AppName, appInfo[0], returnJson);
returnJson);
return Task.CompletedTask;
}; };
RpcServerChannel.BasicConsume(queue, true, "", false, false, null, consumer); Client.SubscribeAsync(rsSubOpts).Wait();
} }
} }
+53 -97
View File
@@ -3,9 +3,12 @@ using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using RabbitMQ.Client; using MQTTnet;
using RabbitMQ.Client.Exceptions; using MQTTnet.Client;
using MQTTnet.Formatter;
using SimApi.Attributes; using SimApi.Attributes;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Configurations; using SimApi.Configurations;
@@ -13,69 +16,51 @@ using SimApi.Helpers;
namespace SimApi; namespace SimApi;
public partial class Synapse public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
{ {
private IServiceProvider Sp { get; } private IServiceProvider Sp { get; } = sp;
private SimApiSynapseOptions Options { get; } private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
private ILogger<Synapse> Logger { get; } private MqttFactory MqttFactory { get; } = new();
public IMqttClient Client { get; set; }
private IConnection Connection { get; set; }
private IModel EventClientChannel { get; set; }
private IModel EventServerChannel { get; set; }
private IModel RpcClientChannel { get; set; }
private IModel RpcServerChannel { get; set; }
private List<RegisterItem> EventRegistry { get; set; } private List<RegisterItem> EventRegistry { get; set; }
private List<RegisterItem> RpcRegistry { get; set; } private List<RegisterItem> RpcRegistry { get; set; }
public Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
{
Logger = logger;
Sp = sp;
Options = simApiOptions.SimApiSynapseOptions;
}
public void Init() public void Init()
{ {
ProcessAttribute(); ProcessAttribute();
Logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options)); logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName)) if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
{ {
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误"); logger.LogCritical("Synapse初始化失败: AppName SysName 不能为空");
} }
Options.AppId ??= Guid.NewGuid().ToString(); Options.AppId ??= Guid.NewGuid().ToString();
Logger.LogInformation("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName, logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
Options.AppName, Options.AppId); Options.SysName, Options.AppName, Options.AppId);
CreateConnection(); CreateConnection();
CheckAndCreateExchange();
//事件客户端 //事件客户端
if (Options.DisableEventClient) if (Options.DisableEventClient)
{ {
Logger.LogWarning("Event Client Disabled: DisableEventClient set true"); logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
} }
else else
{ {
RunEventClient(); logger.LogInformation("Synapse Event Client Ready");
Logger.LogInformation("Event Client Ready");
} }
//RPC客户端 //RPC客户端
if (Options.DisableRpcClient) if (Options.DisableRpcClient)
{ {
Logger.LogWarning("Rpc Client Disabled: DisableEventClient set true"); logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
} }
else else
{ {
RunRpcClient(); RunRpcClient();
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout); logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
} }
if (RpcRegistry.Count > 0) if (RpcRegistry.Count > 0)
@@ -92,10 +77,10 @@ public partial class Synapse
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param) public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
{ {
var res = new SimApiBaseResponse(500, "Rpc Client Disabled!"); var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
if (Options.DisableRpcClient) if (Options.DisableRpcClient)
{ {
Logger.LogError("Rpc Client Disabled!"); logger.LogError("Synapse Rpc Client Disabled!");
} }
else else
{ {
@@ -115,7 +100,7 @@ public partial class Synapse
{ {
if (Options.DisableEventClient) if (Options.DisableEventClient)
{ {
Logger.LogError("Event Client Disabled!"); logger.LogError("Synapse Event Client Disabled!");
} }
else else
{ {
@@ -125,73 +110,43 @@ public partial class Synapse
private void CreateConnection() private void CreateConnection()
{ {
var factory = new ConnectionFactory Client = MqttFactory.CreateMqttClient();
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
.WithCredentials(Options.Username, Options.Password)
.WithClientId($"{Options.AppName}:{Options.AppId}")
.Build();
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
Client.ConnectedAsync += _ =>
{ {
HostName = Options.MqHost, logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
Port = Options.MqPort, return Task.CompletedTask;
VirtualHost = Options.MqVHost,
UserName = Options.MqUser,
Password = Options.MqPass
}; };
try //重连
Client.DisconnectedAsync += async _ =>
{ {
Connection = factory.CreateConnection(); logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
Logger.LogInformation("连接RabbitMQ服务器成功"); await Task.Delay(TimeSpan.FromSeconds(5));
} try
catch (BrokerUnreachableException e)
{
Logger.LogError("连接RabbitMQ失败: \n{Err}", e);
}
}
private IModel CreateChannel(ushort processNum = 0, string desc = "unknow")
{
IModel channel = null;
try
{
var log = $"Channel [{desc}] 创建成功...";
channel = Connection.CreateModel();
if (processNum != 0)
{ {
channel.BasicQos(0, processNum, false); logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
log += $"最大处理器数量: {processNum}"; Client.ConnectAsync(clientOpts).Wait();
} }
catch
Logger.LogInformation(log); {
} logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
catch (ConnectFailureException e) }
{ };
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
}
return channel;
}
private void CheckAndCreateExchange()
{
var channel = CreateChannel(0, "Exchange");
try
{
channel.ExchangeDeclare(Options.SysName, ExchangeType.Topic, true, true, null);
Logger.LogDebug("Register Exchange Success");
}
catch (ConnectFailureException e)
{
Logger.LogError("Failed to declare Exchange.\n {Err}", e);
}
channel.Close();
Logger.LogDebug("Exchange Channel Closed");
} }
private void ProcessAttribute() private void ProcessAttribute()
{ {
EventRegistry = new List<RegisterItem>(); EventRegistry = [];
RpcRegistry = new List<RegisterItem>(); RpcRegistry = [];
var stackTrace = new StackTrace(); var stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod(); var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var assembly = callingMethod.DeclaringType.Assembly; var assembly = callingMethod?.DeclaringType?.Assembly;
var types = assembly.GetTypes(); // 获取程序集中的所有类型 var types = assembly!.GetTypes(); // 获取程序集中的所有类型
foreach (var type in types) foreach (var type in types)
{ {
var methods = type.GetMethods(); // 获取类型中的所有方法 var methods = type.GetMethods(); // 获取类型中的所有方法
@@ -233,15 +188,16 @@ public partial class Synapse
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}"); (current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
var rpcList = RpcRegistry.Aggregate(string.Empty, var rpcList = RpcRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}"); (current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
Logger.LogInformation(">>> Synapse System 读取Event方法:{Event}\n>>>Synapse System 读取RPC方法:{Rpc}", events, rpcList); if (EventRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取Event方法:{Event}", events);
if (RpcRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取RPC方法:{Rpc}", rpcList);
} }
} }
public class RegisterItem public class RegisterItem
{ {
public string Key { get; set; } public string Key { get; init; }
public Type Class { get; set; } public Type Class { get; init; }
public string Method { get; set; } public string Method { get; init; }
} }