动手造轮子:基于 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>();
注册
EventHandlerservices.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
- https://github.com/WeihanLi/ActivityReservation
- https://github.com/WeihanLi/WeihanLi.Redis
- https://redis.io/topics/pubsub
动手造轮子:基于 Redis 实现 EventBus的更多相关文章
- 动手造轮子:实现一个简单的 EventBus
动手造轮子:实现一个简单的 EventBus Intro EventBus 是一种事件发布订阅模式,通过 EventBus 我们可以很方便的实现解耦,将事件的发起和事件的处理的很好的分隔开来,很好的实 ...
- 动手造轮子:实现简单的 EventQueue
动手造轮子:实现简单的 EventQueue Intro 最近项目里有遇到一些并发的问题,想实现一个队列来将并发的请求一个一个串行处理,可以理解为使用消息队列处理并发问题,之前实现过一个简单的 Eve ...
- 动手造轮子:实现一个简单的 AOP 框架
动手造轮子:实现一个简单的 AOP 框架 Intro 最近实现了一个 AOP 框架 -- FluentAspects,API 基本稳定了,写篇文章分享一下这个 AOP 框架的设计. 整体设计 概览 I ...
- 手动造轮子——基于.NetCore的RPC框架DotNetCoreRpc
前言 一直以来对内部服务间使用RPC的方式调用都比较赞同,因为内部间没有这么多限制,最简单明了的方式就是最合适的方式.个人比较喜欢类似Dubbo的那种使用方式,把接口层单独出来,作为服务的契约 ...
- GitHub Android 最火开源项目Top20 GitHub 上的开源项目不胜枚举,越来越多的开源项目正在迁移到GitHub平台上。基于不要重复造轮子的原则,了解当下比较流行的Android与iOS开源项目很是必要。利用这些项目,有时能够让你达到事半功倍的效果。
1. ActionBarSherlock(推荐) ActionBarSherlock应该算得上是GitHub上最火的Android开源项目了,它是一个独立的库,通过一个API和主题,开发者就可以很方便 ...
- 重复造轮子系列——基于Ocelot实现类似支付宝接口模式的网关
重复造轮子系列——基于Ocelot实现类似支付宝接口模式的网关 引言 重复造轮子系列是自己平时的一些总结.有的轮子依赖社区提供的轮子为基础,这里把使用过程的一些觉得有意思的做个分享.有些思路或者方法在 ...
- 重复造轮子系列——基于FastReport设计打印模板实现桌面端WPF套打和商超POS高度自适应小票打印
重复造轮子系列——基于FastReport设计打印模板实现桌面端WPF套打和商超POS高度自适应小票打印 一.引言 桌面端系统经常需要对接各种硬件设备,比如扫描器.读卡器.打印机等. 这里介绍下桌面端 ...
- h5engine造轮子
基于学习的造轮子,这是一个最简单,最基础的一个canvas渲染引擎,通过这个引擎架构,可以很快的学习canvas渲染模式! 地址:https://github.com/RichLiu1023/h5en ...
- 54 个官方 Spring Boot Starters 出炉!别再重复造轮子了…….
在之前的文章,栈长介绍了 Spring Boot Starters,不清楚的可以点击链接进去看下. 前段时间 Spring Boot 2.4.0 也发布了,本文栈长再详细总结下最新的 Spring B ...
随机推荐
- WIN8安装oracle11g时出现不满足最低配置解决办法
Windows8上面安装Oracle11g客户端和服务端时都会出现这样的错误提示:[INS-13001]环境不满足最低要求 产生这种报错的主要原因在于:oracle 11g的配置文件中并没有提供匹配w ...
- 基于Bert的文本情感分类
详细代码已上传到github: click me Abstract: Sentiment classification is the process of analyzing and reaso ...
- 实战Java的反射机制
众所周知,Java要调用某个对象的方法首先需要对象实例化后才能调用. 而实例化对象常见的就是new执行和spring(DI)的依赖注入了. Spring的DI其实就是以反射作为最基础的技术手段. 一. ...
- F#周报2019年第26期
新闻 逐渐演化的.NET Core框架 Visual Studio提示与技巧 Windows Termina(预览) Microsoft在GitHub上的工程师从2000名增加至25000名 视频及幻 ...
- Spring 5.x 、Spring Boot 2.x 、Spring Cloud 与常用技术栈整合
项目 GitHub 地址:https://github.com/heibaiying/spring-samples-for-all 版本说明: Spring: 5.1.3.RELEASE Spring ...
- 【转载】BIO、NIO、AIO
请看原文,排版更佳>转载请注明出处:http://blog.csdn.net/anxpp/article/details/51512200,谢谢! 本文会从传统的BIO到NIO再到AIO自浅至深 ...
- 基于STM32之UART串口通信协议(一)详解
一.前言 1.简介 写的这篇博客,是为了简单讲解一下UART通信协议,以及UART能够实现的一些功能,还有有关使用STM32CubeMX来配置芯片的一些操作,在后面我会以我使用的STM32F429开发 ...
- 开源FTP/SFTP客户端 FileZilla v3.31.0 绿色便携版
下载地址:点我 基本介绍 FileZilla是一种快速.可信赖的FTP客户端以及服务器端开放源代码程式,具有多种特色.直觉的接口.可控性.有条理的界面和管理多站点的简化方式使得Filezilla客户端 ...
- NOIP2002 字串变换题解(双向搜索)
65. [NOIP2002] 字串变换 时间限制:1 s 内存限制:128 MB [问题描述] 已知有两个字串A$, B$及一组字串变换的规则(至多6个规则): A1$ -> B1$ A2$ ...
- [记录]inotifywait+rsync脚本和sersync2服务检测的脚本
1)inotifywait+rsync脚本: #!/bin/bash src=/data/ # 需要同步的源路径 des=data # 目标服务器上 rsync --daemon 发布的名称,rsyn ...