动手造*:实现简单的 EventQueue
动手造*:实现简单的 eventqueue
intro
最近项目里有遇到一些并发的问题,想实现一个队列来将并发的请求一个一个串行处理,可以理解为使用消息队列处理并发问题,之前实现过一个简单的 eventbus
,于是想在 eventbus
的基础上改造一下,加一个队列,改造成类似消息队列的处理模式。消息的处理(consumer)直接使用 .netcore 里的 ihostedservice
来实现了一个简单的后台任务处理。
初步设计
- event 抽象的事件
- eventhandler 处理 event 的方法
- eventstore 保存订阅 event 的 eventhandler
- eventqueue 保存 event 的队列
- eventpublisher 发布 event
- eventconsumer 处理 event 队列里的 event
- eventsubscriptionmanager 管理订阅 event 的 eventhandler
实现代码
eventbase 定义了基本事件信息,事件发生时间以及事件的id:
public abstract class eventbase { [jsonproperty] public datetimeoffset eventat { get; private set; } [jsonproperty] public string eventid { get; private set; } protected eventbase() { this.eventid = guididgenerator.instance.newid(); this.eventat = datetimeoffset.utcnow; } [jsonconstructor] public eventbase(string eventid, datetimeoffset eventat) { this.eventid = eventid; this.eventat = eventat; } }
eventhandler 定义:
public interface ieventhandler { task handle(ieventbase @event); } public interface ieventhandler<in tevent> : ieventhandler where tevent : ieventbase { task handle(tevent @event); } public class eventhandlerbase<tevent> : ieventhandler<tevent> where tevent : eventbase { public virtual task handle(tevent @event) { return task.completedtask; } public task handle(ieventbase @event) { return handle(@event as tevent); } }
eventstore:
public class eventstore { private readonly dictionary<type, type> _eventhandlers = new dictionary<type, type>(); public void add<tevent, teventhandler>() where teventhandler : ieventhandler<tevent> where tevent : eventbase { _eventhandlers.add(typeof(tevent), typeof(teventhandler)); } public object geteventhandler(type eventtype, iserviceprovider serviceprovider) { if (eventtype == null || !_eventhandlers.trygetvalue(eventtype, out var handlertype) || handlertype == null) { return null; } return serviceprovider.getservice(handlertype); } public object geteventhandler(eventbase eventbase, iserviceprovider serviceprovider) => geteventhandler(eventbase.gettype(), serviceprovider); public object geteventhandler<tevent>(iserviceprovider serviceprovider) where tevent : eventbase => geteventhandler(typeof(tevent), serviceprovider); }
eventqueue 定义:
public class eventqueue { private readonly concurrentdictionary<string, concurrentqueue<eventbase>> _eventqueues = new concurrentdictionary<string, concurrentqueue<eventbase>>(); public icollection<string> queues => _eventqueues.keys; public void enqueue<tevent>(string queuename, tevent @event) where tevent : eventbase { var queue = _eventqueues.getoradd(queuename, q => new concurrentqueue<eventbase>()); queue.enqueue(@event); } public bool trydequeue(string queuename, out eventbase @event) { var queue = _eventqueues.getoradd(queuename, q => new concurrentqueue<eventbase>()); return queue.trydequeue(out @event); } public bool tryremovequeue(string queuename) { return _eventqueues.tryremove(queuename, out _); } public bool containsqueue(string queuename) => _eventqueues.containskey(queuename); public concurrentqueue<eventbase> this[string queuename] => _eventqueues[queuename]; }
eventpublisher:
public interface ieventpublisher { task publish<tevent>(string queuename, tevent @event) where tevent : eventbase; } public class eventpublisher : ieventpublisher { private readonly eventqueue _eventqueue; public eventpublisher(eventqueue eventqueue) { _eventqueue = eventqueue; } public task publish<tevent>(string queuename, tevent @event) where tevent : eventbase { _eventqueue.enqueue(queuename, @event); return task.completedtask; } }
eventsubscriptionmanager:
public interface ieventsubscriptionmanager { void subscribe<tevent, teventhandler>() where tevent : eventbase where teventhandler : ieventhandler<tevent>; } public class eventsubscriptionmanager : ieventsubscriptionmanager { private readonly eventstore _eventstore; public eventsubscriptionmanager(eventstore eventstore) { _eventstore = eventstore; } public void subscribe<tevent, teventhandler>() where tevent : eventbase where teventhandler : ieventhandler<tevent> { _eventstore.add<tevent, teventhandler>(); } }
eventconsumer:
public class eventconsumer : backgroundservice { private readonly eventqueue _eventqueue; private readonly eventstore _eventstore; private readonly int maxsemaphorecount = 256; private readonly iserviceprovider _serviceprovider; private readonly ilogger _logger; public eventconsumer(eventqueue eventqueue, eventstore eventstore, iconfiguration configuration, ilogger<eventconsumer> logger, iserviceprovider serviceprovider) { _eventqueue = eventqueue; _eventstore = eventstore; _logger = logger; _serviceprovider = serviceprovider; } protected override async task executeasync(cancellationtoken stoppingtoken) { using (var semaphore = new semaphoreslim(environment.processorcount, maxsemaphorecount)) { while (!stoppingtoken.iscancellationrequested) { var queues = _eventqueue.queues; if (queues.count > 0) { await task.whenall( queues .select(async queuename => { if (!_eventqueue.containsqueue(queuename)) { return; } try { await semaphore.waitasync(stoppingtoken); // if (_eventqueue.trydequeue(queuename, out var @event)) { var eventhandler = _eventstore.geteventhandler(@event, _serviceprovider); if (eventhandler is ieventhandler handler) { _logger.loginformation( "handler {handlertype} begin to handle event {eventtype}, eventid: {eventid}, eventinfo: {eventinfo}", eventhandler.gettype().fullname, @event.gettype().fullname, @event.eventid, jsonconvert.serializeobject(@event)); try { await handler.handle(@event); } catch (exception e) { _logger.logerror(e, "event {eventid} handled exception", @event.eventid); } finally { _logger.loginformation("event {eventid} handled", @event.eventid); } } else { _logger.logwarning( "no event handler registered for event {eventtype}, eventid: {eventid}, eventinfo: {eventinfo}", @event.gettype().fullname, @event.eventid, jsonconvert.serializeobject(@event)); } } } catch (exception ex) { _logger.logerror(ex, "error running eventconsumer"); } finally { semaphore.release(); } }) ); } await task.delay(50, stoppingtoken); } } } }
为了方便使用定义了一个 event 扩展方法:
public static iservicecollection addevent(this iservicecollection services) { services.tryaddsingleton<eventstore>(); services.tryaddsingleton<eventqueue>(); services.tryaddsingleton<ieventpublisher, eventpublisher>(); services.tryaddsingleton<ieventsubscriptionmanager, eventsubscriptionmanager>(); services.addsingleton<ihostedservice, eventconsumer>(); return services; }
使用示例
定义 pageviewevent
记录请求信息:
public class pageviewevent : eventbase { public string path { get; set; } }
这里作为示例只记录了请求的path信息,实际使用可以增加更多需要记录的信息
定义 pagevieweventhandler
,处理 pageviewevent
public class pagevieweventhandler : eventhandlerbase<pageviewevent> { private readonly ilogger _logger; public pagevieweventhandler(ilogger<pagevieweventhandler> logger) { _logger = logger; } public override task handle(pageviewevent @event) { _logger.loginformation($"handle pageviewevent: {jsonconvert.serializeobject(@event)}"); return task.completedtask; } }
这个 handler 里什么都没做只是输出一个日志
这个示例项目定义了一个记录请求路径的事件以及一个发布请求记录事件的中间件
// 发布 event 的中间件 app.use(async (context, next) => { var eventpublisher = context.requestservices.getrequiredservice<ieventpublisher>(); await eventpublisher.publish("pageview", new pageviewevent() { path = context.request.path.value }); await next(); });
startup 配置:
public void configureservices(iservicecollection services) { // ... services.addevent(); services.addsingleton<pagevieweventhandler>();// 注册 handler } // this method gets called by the runtime. use this method to configure the http request pipeline. public void configure(iapplicationbuilder app, ihostingenvironment env, ieventsubscriptionmanager eventsubscriptionmanager) { eventsubscriptionmanager.subscribe<pageviewevent, pagevieweventhandler>(); app.use(async (context, next) => { var eventpublisher = context.requestservices.getrequiredservice<ieventpublisher>(); await eventpublisher.publish("pageview", new pageviewevent() { path = context.request.path.value }); await next(); }); // ... }
使用效果:
more
注:只是一个初步设计,基本可以实现功能,还是有些不足,实际应用的话还有一些要考虑的事情
-
consumer
消息逻辑,现在的实现有些问题,我们的应用场景目前比较简单还可以满足,如果事件比较多就会而且每个事件可能处理需要的时间长短不一样,会导致在一个批次中执行的event
中已经完成的事件要等待其他还没完成的事件完成之后才能继续取下一个事件,理想的消费模式应该是各个队列相互独立,在同一个队列中保持顺序消费即可 - 上面示例的
eventstore
的实现只是简单的实现了一个事件一个handler
的处理情况,实际业务场景中很可能会有一个事件需要多个handler
的情况 - 这个实现是基于内存的,如果要在分布式场景下使用就不适用了,需要自己实现一下基于redis或者数据库的以满足分布式的需求
- and more...
上面所有的代码可以在 github 上获取,示例项目 github 地址:https://github.com/weihanli/aspnetcoreplayground/tree/master/testwebapplication
reference
上一篇: 如何蒸扇贝?一种好吃又简单的做法!
下一篇: 黑木耳粉减肥,黑木耳粉真的能减肥吗