2025-04-15 11:15:22 +08:00
|
|
|
|
using Confluent.Kafka;
|
2025-04-17 13:35:08 +08:00
|
|
|
|
using JiShe.CollectBus.Common.Consts;
|
2025-04-17 14:39:14 +08:00
|
|
|
|
using JiShe.CollectBus.Common.Extensions;
|
2025-04-16 09:54:21 +08:00
|
|
|
|
using JiShe.CollectBus.Kafka.AdminClient;
|
2025-04-15 11:15:22 +08:00
|
|
|
|
using JiShe.CollectBus.Kafka.Attributes;
|
|
|
|
|
|
using JiShe.CollectBus.Kafka.Consumer;
|
|
|
|
|
|
using Microsoft.AspNetCore.Builder;
|
2025-04-17 13:35:08 +08:00
|
|
|
|
using Microsoft.Extensions.Configuration;
|
2025-04-15 11:15:22 +08:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
using Microsoft.Extensions.Hosting;
|
2025-04-15 15:49:22 +08:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
2025-04-17 14:39:14 +08:00
|
|
|
|
using Microsoft.Extensions.Options;
|
2025-04-15 11:15:22 +08:00
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
|
|
namespace JiShe.CollectBus.Kafka
|
|
|
|
|
|
{
|
|
|
|
|
|
public static class KafkaSubcribesExtensions
|
|
|
|
|
|
{
|
2025-04-17 13:01:26 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 添加Kafka订阅
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="app"></param>
|
|
|
|
|
|
/// <param name="assembly"></param>
|
|
|
|
|
|
public static void UseKafkaSubscribers(this IServiceProvider provider)
|
|
|
|
|
|
{
|
|
|
|
|
|
var lifetime = provider.GetRequiredService<IHostApplicationLifetime>();
|
2025-04-17 11:53:29 +08:00
|
|
|
|
|
2025-04-17 14:39:14 +08:00
|
|
|
|
//初始化主题信息
|
|
|
|
|
|
var kafkaAdminClient = provider.GetRequiredService<IAdminClientService>();
|
|
|
|
|
|
var kafkaOptions = provider.GetRequiredService<IOptions<KafkaOptionConfig>>();
|
|
|
|
|
|
|
|
|
|
|
|
List<string> topics = ProtocolConstExtensions.GetAllTopicNamesByIssued();
|
|
|
|
|
|
topics.AddRange(ProtocolConstExtensions.GetAllTopicNamesByReceived());
|
|
|
|
|
|
|
|
|
|
|
|
foreach (var item in topics)
|
|
|
|
|
|
{
|
|
|
|
|
|
kafkaAdminClient.CreateTopicAsync(item, kafkaOptions.Value.NumPartitions, kafkaOptions.Value.KafkaReplicationFactor).ConfigureAwait(false).GetAwaiter().GetResult();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-17 13:01:26 +08:00
|
|
|
|
lifetime.ApplicationStarted.Register(() =>
|
|
|
|
|
|
{
|
|
|
|
|
|
var logger = provider.GetRequiredService<ILogger<CollectBusKafkaModule>>();
|
|
|
|
|
|
int threadCount = 0;
|
|
|
|
|
|
int topicCount = 0;
|
|
|
|
|
|
var assemblyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(assemblyPath))
|
|
|
|
|
|
{
|
|
|
|
|
|
logger.LogInformation($"kafka订阅未能找到程序路径");
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
var dllFiles = Directory.GetFiles(assemblyPath, "*.dll");
|
|
|
|
|
|
foreach (var file in dllFiles)
|
|
|
|
|
|
{
|
|
|
|
|
|
// 跳过已加载的程序集
|
|
|
|
|
|
var assemblyName = AssemblyName.GetAssemblyName(file);
|
|
|
|
|
|
var existingAssembly = AppDomain.CurrentDomain.GetAssemblies()
|
|
|
|
|
|
.FirstOrDefault(a => a.GetName().FullName == assemblyName.FullName);
|
|
|
|
|
|
var assembly = existingAssembly ?? Assembly.LoadFrom(file);
|
|
|
|
|
|
// 实现IKafkaSubscribe接口
|
|
|
|
|
|
var subscribeTypes = assembly.GetTypes().Where(type =>
|
|
|
|
|
|
typeof(IKafkaSubscribe).IsAssignableFrom(type) &&
|
|
|
|
|
|
!type.IsAbstract && !type.IsInterface).ToList(); ;
|
|
|
|
|
|
if (subscribeTypes.Count == 0)
|
|
|
|
|
|
continue;
|
|
|
|
|
|
foreach (var subscribeType in subscribeTypes)
|
|
|
|
|
|
{
|
|
|
|
|
|
var subscribes = provider.GetServices(subscribeType).ToList();
|
|
|
|
|
|
subscribes.ForEach(subscribe =>
|
|
|
|
|
|
{
|
|
|
|
|
|
if (subscribe!=null)
|
|
|
|
|
|
{
|
2025-04-17 14:39:14 +08:00
|
|
|
|
Tuple<int, int> tuple = BuildKafkaSubscriber(subscribe, provider, logger, kafkaOptions.Value);
|
2025-04-17 13:01:26 +08:00
|
|
|
|
threadCount += tuple.Item1;
|
|
|
|
|
|
topicCount += tuple.Item2;
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
logger.LogInformation($"kafka订阅主题:{topicCount}数,共启动:{threadCount}线程");
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
2025-04-17 11:53:29 +08:00
|
|
|
|
|
|
|
|
|
|
public static void UseKafkaSubscribers(this IApplicationBuilder app, Assembly assembly)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
|
|
|
|
|
var provider = app.ApplicationServices;
|
|
|
|
|
|
var lifetime = provider.GetRequiredService<IHostApplicationLifetime>();
|
2025-04-17 14:39:14 +08:00
|
|
|
|
//初始化主题信息
|
|
|
|
|
|
var kafkaAdminClient = provider.GetRequiredService<IAdminClientService>();
|
|
|
|
|
|
var kafkaOptions = provider.GetRequiredService<IOptions<KafkaOptionConfig>>();
|
|
|
|
|
|
|
|
|
|
|
|
List<string> topics = ProtocolConstExtensions.GetAllTopicNamesByIssued();
|
|
|
|
|
|
topics.AddRange(ProtocolConstExtensions.GetAllTopicNamesByReceived());
|
|
|
|
|
|
|
|
|
|
|
|
foreach (var item in topics)
|
|
|
|
|
|
{
|
|
|
|
|
|
kafkaAdminClient.CreateTopicAsync(item, kafkaOptions.Value.NumPartitions, kafkaOptions.Value.KafkaReplicationFactor).ConfigureAwait(false).GetAwaiter().GetResult();
|
|
|
|
|
|
}
|
2025-04-15 11:15:22 +08:00
|
|
|
|
|
|
|
|
|
|
lifetime.ApplicationStarted.Register(() =>
|
|
|
|
|
|
{
|
2025-04-16 09:54:21 +08:00
|
|
|
|
var logger = provider.GetRequiredService<ILogger<CollectBusKafkaModule>>();
|
|
|
|
|
|
int threadCount = 0;
|
|
|
|
|
|
int topicCount = 0;
|
2025-04-17 11:53:29 +08:00
|
|
|
|
var subscribeTypes = assembly.GetTypes()
|
2025-04-17 11:42:35 +08:00
|
|
|
|
.Where(t => typeof(IKafkaSubscribe).IsAssignableFrom(t))
|
|
|
|
|
|
.ToList();
|
|
|
|
|
|
|
2025-04-17 11:53:29 +08:00
|
|
|
|
if (subscribeTypes.Count == 0) return;
|
|
|
|
|
|
foreach (var subscribeType in subscribeTypes)
|
|
|
|
|
|
{
|
|
|
|
|
|
var subscribes = provider.GetServices(subscribeType).ToList();
|
|
|
|
|
|
subscribes.ForEach(subscribe => {
|
|
|
|
|
|
|
2025-04-17 13:01:26 +08:00
|
|
|
|
if (subscribe != null)
|
2025-04-17 11:53:29 +08:00
|
|
|
|
{
|
2025-04-17 14:39:14 +08:00
|
|
|
|
Tuple<int, int> tuple = BuildKafkaSubscriber(subscribe, provider, logger, kafkaOptions.Value);
|
2025-04-17 11:53:29 +08:00
|
|
|
|
threadCount += tuple.Item1;
|
|
|
|
|
|
topicCount += tuple.Item2;
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
2025-04-16 09:54:21 +08:00
|
|
|
|
logger.LogInformation($"kafka订阅主题:{topicCount}数,共启动:{threadCount}线程");
|
2025-04-15 11:15:22 +08:00
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 构建Kafka订阅
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="subscribe"></param>
|
|
|
|
|
|
/// <param name="provider"></param>
|
2025-04-17 14:39:14 +08:00
|
|
|
|
private static Tuple<int,int> BuildKafkaSubscriber(object subscribe, IServiceProvider provider,ILogger<CollectBusKafkaModule> logger, KafkaOptionConfig kafkaOptionConfig)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-15 15:49:22 +08:00
|
|
|
|
var subscribedMethods = subscribe.GetType().GetMethods()
|
|
|
|
|
|
.Select(m => new { Method = m, Attribute = m.GetCustomAttribute<KafkaSubscribeAttribute>() })
|
|
|
|
|
|
.Where(x => x.Attribute != null)
|
|
|
|
|
|
.ToArray();
|
2025-04-17 14:39:14 +08:00
|
|
|
|
//var configuration = provider.GetRequiredService<IConfiguration>();
|
2025-04-16 09:54:21 +08:00
|
|
|
|
int threadCount = 0;
|
2025-04-15 15:49:22 +08:00
|
|
|
|
foreach (var sub in subscribedMethods)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-17 14:39:14 +08:00
|
|
|
|
int partitionCount = kafkaOptionConfig.NumPartitions;
|
2025-04-17 13:35:08 +08:00
|
|
|
|
//var adminClientService = provider.GetRequiredService<IAdminClientService>();
|
|
|
|
|
|
//int partitionCount = sub.Attribute!.TaskCount==-1?adminClientService.GetTopicPartitionsNum(sub.Attribute!.Topic) : sub.Attribute!.TaskCount;
|
2025-04-16 09:54:21 +08:00
|
|
|
|
if (partitionCount <= 0)
|
|
|
|
|
|
partitionCount = 1;
|
|
|
|
|
|
for (int i = 0; i < partitionCount; i++)
|
|
|
|
|
|
{
|
|
|
|
|
|
Task.Run(() => StartConsumerAsync(provider, sub.Attribute!, sub.Method, subscribe, logger));
|
|
|
|
|
|
threadCount++;
|
|
|
|
|
|
}
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
2025-04-16 09:54:21 +08:00
|
|
|
|
return Tuple.Create(threadCount, subscribedMethods.Length);
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 启动后台消费线程
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="config"></param>
|
|
|
|
|
|
/// <param name="attr"></param>
|
|
|
|
|
|
/// <param name="method"></param>
|
|
|
|
|
|
/// <param name="consumerInstance"></param>
|
|
|
|
|
|
/// <returns></returns>
|
2025-04-16 09:54:21 +08:00
|
|
|
|
private static async Task StartConsumerAsync(IServiceProvider provider, KafkaSubscribeAttribute attr,MethodInfo method, object subscribe, ILogger<CollectBusKafkaModule> logger)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-15 15:49:22 +08:00
|
|
|
|
var consumerService = provider.GetRequiredService<IConsumerService>();
|
2025-04-17 13:56:17 +08:00
|
|
|
|
|
|
|
|
|
|
if (attr.EnableBatch)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-17 13:56:17 +08:00
|
|
|
|
await consumerService.SubscribeBatchAsync<dynamic>(attr.Topic, async (message) =>
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-17 13:56:17 +08:00
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
// 处理消息
|
|
|
|
|
|
return await ProcessMessageAsync(message, method, subscribe);
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (ConsumeException ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
// 处理消费错误
|
|
|
|
|
|
logger.LogError($"kafka批量消费异常:{ex.Message}");
|
|
|
|
|
|
}
|
|
|
|
|
|
return await Task.FromResult(false);
|
2025-04-17 14:39:14 +08:00
|
|
|
|
}, attr.GroupId, attr.BatchSize,attr.BatchTimeout);
|
2025-04-17 13:56:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
else
|
|
|
|
|
|
{
|
|
|
|
|
|
await consumerService.SubscribeAsync<dynamic>(attr.Topic, async (message) =>
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
2025-04-17 13:56:17 +08:00
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
// 处理消息
|
|
|
|
|
|
return await ProcessMessageAsync(message, method, subscribe);
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (ConsumeException ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
// 处理消费错误
|
|
|
|
|
|
logger.LogError($"kafka消费异常:{ex.Message}");
|
|
|
|
|
|
}
|
|
|
|
|
|
return await Task.FromResult(false);
|
2025-04-17 14:39:14 +08:00
|
|
|
|
}, attr.GroupId);
|
2025-04-17 13:56:17 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-15 18:03:51 +08:00
|
|
|
|
|
2025-04-15 15:49:22 +08:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 处理消息
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="message"></param>
|
|
|
|
|
|
/// <param name="method"></param>
|
|
|
|
|
|
/// <param name="subscribe"></param>
|
|
|
|
|
|
/// <returns></returns>
|
2025-04-16 18:26:25 +08:00
|
|
|
|
private static async Task<bool> ProcessMessageAsync(dynamic message, MethodInfo method, object subscribe)
|
2025-04-15 11:15:22 +08:00
|
|
|
|
{
|
|
|
|
|
|
var parameters = method.GetParameters();
|
2025-04-15 18:03:51 +08:00
|
|
|
|
bool isGenericTask = method.ReturnType.IsGenericType
|
|
|
|
|
|
&& method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>);
|
|
|
|
|
|
bool existParameters = parameters.Length > 0;
|
2025-04-16 18:26:25 +08:00
|
|
|
|
//dynamic? messageObj= null;
|
|
|
|
|
|
//if (existParameters)
|
|
|
|
|
|
//{
|
|
|
|
|
|
// var paramType = parameters[0].ParameterType;
|
|
|
|
|
|
// messageObj = paramType == typeof(string) ? message : message.Deserialize(paramType);
|
|
|
|
|
|
//}
|
2025-04-15 18:03:51 +08:00
|
|
|
|
if (isGenericTask)
|
|
|
|
|
|
{
|
2025-04-16 18:26:25 +08:00
|
|
|
|
object? result = await (Task<ISubscribeAck>)method.Invoke(subscribe, existParameters? new[] { message } :null)!;
|
2025-04-15 16:45:10 +08:00
|
|
|
|
if (result is ISubscribeAck ackResult)
|
|
|
|
|
|
{
|
|
|
|
|
|
return ackResult.Ack;
|
|
|
|
|
|
}
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
|
|
|
|
|
else
|
|
|
|
|
|
{
|
2025-04-16 18:26:25 +08:00
|
|
|
|
object? result = method.Invoke(subscribe, existParameters ? new[] { message } : null);
|
2025-04-15 16:45:10 +08:00
|
|
|
|
if (result is ISubscribeAck ackResult)
|
|
|
|
|
|
{
|
|
|
|
|
|
return ackResult.Ack;
|
|
|
|
|
|
}
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
2025-04-15 15:49:22 +08:00
|
|
|
|
return false;
|
2025-04-15 11:15:22 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|