using Confluent.Kafka; using DeviceDetectorNET; using JiShe.CollectBus.Common.Enums; using JiShe.CollectBus.Common.Helpers; using JiShe.CollectBus.Kafka.Attributes; using JiShe.CollectBus.Kafka.Consumer; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using static Confluent.Kafka.ConfigPropertyNames; namespace JiShe.CollectBus.Kafka { public static class KafkaSubcribesExtensions { /// /// 添加Kafka订阅 /// /// /// public static void UseKafkaSubscribers(this IApplicationBuilder app, Assembly assembly) { var subscribeTypes = assembly.GetTypes() .Where(t => typeof(IKafkaSubscribe).IsAssignableFrom(t)) .ToList(); if (subscribeTypes.Count == 0) return; var provider = app.ApplicationServices; var lifetime = provider.GetRequiredService(); lifetime.ApplicationStarted.Register(() => { foreach (var subscribeType in subscribeTypes) { var subscribes = provider.GetServices(subscribeType).ToList(); subscribes.ForEach(subscribe => { if(subscribe is IKafkaSubscribe) { BuildKafkaSubscriber(subscribe, provider); } }); } }); } /// /// 构建Kafka订阅 /// /// /// private static void BuildKafkaSubscriber(object subscribe, IServiceProvider provider) { var subscribedMethods = subscribe.GetType().GetMethods() .Select(m => new { Method = m, Attribute = m.GetCustomAttribute() }) .Where(x => x.Attribute != null) .ToArray(); foreach (var sub in subscribedMethods) { Task.Run(() => StartConsumerAsync(provider, sub.Attribute!, sub.Method, subscribe)); } } /// /// 启动后台消费线程 /// /// /// /// /// /// private static async Task StartConsumerAsync(IServiceProvider provider, KafkaSubscribeAttribute attr,MethodInfo method, object subscribe) { var consumerService = provider.GetRequiredService(); var logger = provider.GetRequiredService>(); await consumerService.SubscribeAsync(attr.Topics, async (message) => { try { // 处理消息 return await ProcessMessageAsync(message, method, subscribe); } catch (ConsumeException ex) { // 处理消费错误 logger.LogError($"kafka消费异常:{ex.Message}"); } return await Task.FromResult(false); }); } /// /// 处理消息 /// /// /// /// /// private static async Task ProcessMessageAsync(string message, MethodInfo method, object subscribe) { var parameters = method.GetParameters(); bool isGenericTask = method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>); bool existParameters = parameters.Length > 0; dynamic? messageObj= null; if (existParameters) { var paramType = parameters[0].ParameterType; messageObj = paramType == typeof(string) ? message : message.Deserialize(paramType); } if (isGenericTask) { object? result = await (Task)method.Invoke(subscribe, existParameters? new[] { messageObj }:null)!; if (result is ISubscribeAck ackResult) { return ackResult.Ack; } } else { object? result = method.Invoke(subscribe, existParameters ? new[] { messageObj } : null); if (result is ISubscribeAck ackResult) { return ackResult.Ack; } } return false; } } }