Monday, June 3, 2013

Domain Events - Redis PubSub - Publishing & History

This is my fifth post about events, you can read the the first one here.

In my last post, I introduce Redis and talk about how to subscribe to events. In this post I'll discuss how to publish events to Redis and keep a running history of events.

There are a lot of ways to handle which events will be sent over to Redis, and I debated for a while on what would work out the best. I thought about marking IEvent classes with an attribute, or a new interface, but decided on just sending all events over to Redis. Redis is very fast, so the wait time will be minimal, and if you ever decide you want to subscribe to an event, you don't have to make any code changes on the publisher.

To keep responsibilities separate, I created a new implementation of IEventer that just handles the Redis publish. This has another advantage in that we could create configuration flags to enable/disable the entire PubSub system. I use this pattern of chaining a lot for Repositories and CachedRepositories.

When Raise is called, the first thing we do is call raise on our normal IEventer implementation. Then we connect up to Redis, and publish the serialized event.

Lets expand on this a bit more by creating a history of events. We'll use the Pipelining feature of Redis to send over several commands more efficiently.

I hard-coded the maximum length of the history, but you should probably make this a configuration value.

It would be just as easy to create a controller that lists the history, and has a method to "replay" the event on a targeted server, or all of them.