事件溯源模式 (Event Sourcing Pattern)¶
什么是事件溯源模式?¶
事件溯源(Event Sourcing)是一种持久化模式,它通过将状态改变记录为事件序列来存储状态。
核心思想:不直接保存当前状态,而是保存导致状态变化的所有事件。
核心概念¶
- 事件(Event):状态改变的不可变记录
- 聚合(Aggregate):事件序列重组后的状态
- 事件存储(Event Store):持久化事件的存储
与 CQRS / CRUD 的关系¶
| 维度 | CRUD | 事件溯源 | CQRS |
|---|---|---|---|
| 存储内容 | 当前状态的快照 | 状态变更事件序列 | 写模型 + 读模型分离 |
| 历史追溯 | 需要额外审计表 | 天生拥有完整时间线 | 取决于底层存储 |
| 查询方式 | 直接查表 | 重放事件重建后查询 | 查询为读优化的投影 |
| 组合关系 | 对立面 | 常与 CQRS 一起使用 | 描述读写分离,与事件溯源正交 |
与 CQRS 的分工:CQRS 描述"读模型与写模型分离",事件溯源描述"写入侧如何持久化"—— 事件存储作为写模型,投影作为读模型,两者正交、经常成对出现。
问题场景与解决方案¶
反例:只保存最新余额,转账历史就丢了,无法回答"钱是什么时候被谁改的"。
正例:每笔交易都是不可变事件,账户状态由事件日志重放得出。
// 正例:事件日志 + fold 重放
#include <variant>
#include <vector>
struct Deposit { double amount; };
struct Withdrawal { double amount; };
using Txn = std::variant<Deposit, Withdrawal>;
double apply(double bal, const Txn& t) {
return std::visit([&](const auto& e) {
using T = std::decay_t<decltype(e)>;
if constexpr (std::is_same_v<T, Deposit>) return bal + e.amount;
else return bal - e.amount;
}, t);
}
double replay(const std::vector<Txn>& ledger) {
double balance = 0;
for (const auto& t : ledger) balance = apply(balance, t);
return balance; // 状态 = 对事件做 fold 的结果
}
// 用法:状态 = 事件重放的结果
std::vector<Txn> ledger = {Deposit{100.0}, Withdrawal{30.0}, Deposit{50.0}};
// replay(ledger) == 120,且每一步都可审计
代码实现¶
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <functional>
// 事件基类
class Event {
public:
virtual ~Event() = default;
virtual std::string type() const = 0;
virtual std::string serialize() const = 0;
};
// 具体事件
class UserCreatedEvent : public Event {
public:
std::string name;
std::string email;
std::string type() const override { return "UserCreated"; }
std::string serialize() const override {
return name + ":" + email;
}
};
class UserUpdatedEvent : public Event {
public:
std::string newName;
std::string type() const override { return "UserUpdated"; }
std::string serialize() const override { return newName; }
};
// 事件存储
class EventStore {
public:
void append(const Event& event) {
events_.push_back(&event);
}
const std::vector<const Event*>& getEvents() const { return events_; }
private:
std::vector<const Event*> events_;
};
// 聚合根
class User {
public:
int id;
std::string name;
std::string email;
int version = 0;
void apply(const Event& event) {
if (auto* created = dynamic_cast<const UserCreatedEvent*>(&event)) {
name = created->name;
email = created->email;
} else if (auto* updated = dynamic_cast<const UserUpdatedEvent*>(&event)) {
name = updated->newName;
}
version++;
}
};
// 命令处理器
class CommandHandler {
public:
void handleCreate(const UserCreatedEvent& event, EventStore& store) {
store.append(event);
std::cout << "User created: " << event.name << "\n";
}
void handleUpdate(const UserUpdatedEvent& event, EventStore& store) {
store.append(event);
std::cout << "User updated: " << event.newName << "\n";
}
};
最佳实践¶
- 事件不可变
- 使用事件版本控制
- 投影到读取模型
示例¶
这个主题的可运行版本:
总结¶
事件溯源通过保存事件历史,提供完整的状态变更审计能力。