动手造*:基于 Redis 实现 EventBus
动手造*:基于 redis 实现 eventbus
intro
上次我们造了一个简单的基于内存的 eventbus
,但是如果要跨系统的话就不合适了,所以有了这篇基于 redis
的 eventbus
探索。
本文的实现是基于 stackexchange.redis
来实现的。
rediseventstore
实现
既然要实现跨系统的 eventbus
再使用基于内存的 eventstore 自然不行,因此这里基于 redis 设计了一个 eventstoreinredis
,基于 redis 的 hash 来实现,以 event 的 eventkey 作为 fieldname,以 event 对应的 eventhandler 作为 value。
eventstoreinredis
实现:
public class eventstoreinredis : ieventstore { protected readonly string eventscachekey; protected readonly ilogger logger; private readonly irediswrapper wrapper; public eventstoreinredis(ilogger<eventstoreinredis> logger) { logger = logger; wrapper = new rediswrapper(redisconstants.eventstoreprefix); eventscachekey = redismanager.redisconfiguration.eventstorecachekey; } public bool addsubscription<tevent, teventhandler>() where tevent : ieventbase where teventhandler : ieventhandler<tevent> { var eventkey = geteventkey<tevent>(); var handlertype = typeof(teventhandler); if (wrapper.database.hashexists(eventscachekey, eventkey)) { var handlers = wrapper.unwrap<hashset<type>>(wrapper.database.hashget(eventscachekey, eventkey)); if (handlers.contains(handlertype)) { return false; } handlers.add(handlertype); wrapper.database.hashset(eventscachekey, eventkey, wrapper.wrap(handlers)); return true; } else { return wrapper.database.hashset(eventscachekey, eventkey, wrapper.wrap(new hashset<type> { handlertype }), stackexchange.redis.when.notexists); } } public bool clear() { return wrapper.database.keydelete(eventscachekey); } public icollection<type> geteventhandlertypes<tevent>() where tevent : ieventbase { var eventkey = geteventkey<tevent>(); return wrapper.unwrap<hashset<type>>(wrapper.database.hashget(eventscachekey, eventkey)); } public string geteventkey<tevent>() { return typeof(tevent).fullname; } public bool hassubscriptionsforevent<tevent>() where tevent : ieventbase { var eventkey = geteventkey<tevent>(); return wrapper.database.hashexists(eventscachekey, eventkey); } public bool removesubscription<tevent, teventhandler>() where tevent : ieventbase where teventhandler : ieventhandler<tevent> { var eventkey = geteventkey<tevent>(); var handlertype = typeof(teventhandler); if (!wrapper.database.hashexists(eventscachekey, eventkey)) { return false; } var handlers = wrapper.unwrap<hashset<type>>(wrapper.database.hashget(eventscachekey, eventkey)); if (!handlers.contains(handlertype)) { return false; } handlers.remove(handlertype); wrapper.database.hashset(eventscachekey, eventkey, wrapper.wrap(handlers)); return true; } }
rediswrapper
及更具体的代码可以参考我的 redis 的扩展的实现 https://github.com/weihanli/weihanli.redis
rediseventbus
实现
rediseventbus 是基于 redis 的 pub/sub 实现的,实现的感觉还有一些小问题,我想确保每个客户端注册的时候每个 eventhandler
即使多次注册也只注册一次,但是还没找到一个好的实现,如果你有什么想法欢迎指出,和我一起交流。具体的实现细节如下:
public class rediseventbus : ieventbus { private readonly ieventstore _eventstore; private readonly isubscriber _subscriber; private readonly iserviceprovider _serviceprovider; public rediseventbus(ieventstore eventstore, iconnectionmultiplexer connectionmultiplexer, iserviceprovider serviceprovider) { _eventstore = eventstore; _serviceprovider = serviceprovider; _subscriber = connectionmultiplexer.getsubscriber(); } private string getchannelprefix<tevent>() where tevent : ieventbase { var eventkey = _eventstore.geteventkey<tevent>(); var channelprefix = $"{redismanager.redisconfiguration.eventbuschannelprefix}{redismanager.redisconfiguration.keyseparator}{eventkey}{redismanager.redisconfiguration.keyseparator}"; return channelprefix; } private string getchannelname<tevent, teventhandler>() where tevent : ieventbase where teventhandler : ieventhandler<tevent> => getchannelname<tevent>(typeof(teventhandler)); private string getchannelname<tevent>(type eventhandlertype) where tevent : ieventbase { var channelprefix = getchannelprefix<tevent>(); var channelname = $"{channelprefix}{eventhandlertype.fullname}"; return channelname; } public bool publish<tevent>(tevent @event) where tevent : ieventbase { if (!_eventstore.hassubscriptionsforevent<tevent>()) { return false; } var eventdata = @event.tojson(); var handlertypes = _eventstore.geteventhandlertypes<tevent>(); foreach (var handlertype in handlertypes) { var handlerchannelname = getchannelname<tevent>(handlertype); _subscriber.publish(handlerchannelname, eventdata); } return true; } public bool subscribe<tevent, teventhandler>() where tevent : ieventbase where teventhandler : ieventhandler<tevent> { _eventstore.addsubscription<tevent, teventhandler>(); var channelname = getchannelname<tevent, teventhandler>(); //// todo: if current client subscribed the channel //if (true) //{ _subscriber.subscribe(channelname, async (channel, eventmessage) => { var eventdata = eventmessage.tostring().jsontotype<tevent>(); var handler = _serviceprovider.getserviceorcreateinstance<teventhandler>(); if (null != handler) { await handler.handle(eventdata).configureawait(false); } }); return true; //} //return false; } public bool unsubscribe<tevent, teventhandler>() where tevent : ieventbase where teventhandler : ieventhandler<tevent> { _eventstore.removesubscription<tevent, teventhandler>(); var channelname = getchannelname<tevent, teventhandler>(); //// todo: if current client subscribed the channel //if (true) //{ _subscriber.unsubscribe(channelname); return true; //} //return false; } }
使用示例:
使用起来大体上和上一篇使用一致,只是在初始化注入服务的时候,我们需要把 ieventbus
和 ieventstore
替换为对应 redis 的实现即可。
-
注册服务
services.addsingleton<ieventbus, rediseventbus>(); services.addsingleton<ieventstore, eventstoreinredis>();
-
注册
eventhandler
services.addsingleton<noticevieweventhandler>();
-
订阅事件
eventbus.subscribe<noticeviewevent, noticevieweventhandler>();
-
发布事件
[httpget("{path}")] public async task<iactionresult> getbypath(string path, cancellationtoken cancellationtoken, [fromservices]ieventbus eventbus) { var notice = await _repository.fetchasync(n => n.noticecustompath == path, cancellationtoken); if (notice == null) { return notfound(); } eventbus.publish(new noticeviewevent { noticeid = notice.noticeid }); return ok(notice); }
memo
如果要实现基于消息队列的事件处理,需要注意,消息可能会重复,可能会需要在事件处理中注意一下业务的幂等性或者对消息对一个去重处理。
我在使用 redis 的事件处理中使用了一个基于 redis 原子递增的特性设计的一个防火墙,从而实现一段时间内某一个消息id只会被处理一次,实现源码:https://github.com/weihanli/activityreservation/blob/dev/activityreservation.helper/events/noticeviewevent.cs
public class noticeviewevent : eventbase { public guid noticeid { get; set; } // userid // ip // ... } public class noticevieweventhandler : ieventhandler<noticeviewevent> { public async task handle(noticeviewevent @event) { var firewallclient = redismanager.getfirewallclient($"{nameof(noticevieweventhandler)}_{@event.eventid}", timespan.fromminutes(5)); if (await firewallclient.hitasync()) { await dependencyresolver.current.tryinvokeserviceasync<reservationdbcontext>(async dbcontext => { //var notice = await dbcontext.notices.findasync(@event.noticeid); //notice.noticevisitcount += 1; //await dbcontext.savechangesasync(); var conn = dbcontext.database.getdbconnection(); await conn.executeasync($@"update tabnotice set noticevisitcount = noticevisitcount +1 where noticeid = @noticeid", new { @event.noticeid }); }); } } }
reference
上一篇: 什么叫碰巧