.net - EventStore嵌入式客户端如何使用?

标签 .net database eventstoredb

似乎没有关于如何使用 EventStore.Client.Embedded nuget 包设置、运行和连接到嵌入式 EventStore 客户端的文档。使用以下代码:

ClusterVNode node = EmbeddedVNodeBuilder
    .AsSingleNode()
    .RunInMemory()
    .OnDefaultEndpoints()
    .Build();

var connection = EmbeddedEventStoreConnection.Create(node);
await connection.ConnectAsync();
var sampleEventData = new EventData(Guid.NewGuid(), "myTestEvent", false, new byte[] { 6, 10, 15 }, null);
WriteResult writeResult = await connection.AppendToStreamAsync("sampleStream, ExpectedVersion.NoStream, sampleEventData);

AppendToStreamAsync 行之前一切似乎都正常,它抛出以下异常:

Expected response of EventStore.Core.Messages.ClientMessage+WriteEventsCompleted, received EventStore.Core.Messages.ClientMessage+NotHandled instead.

绕过这个异常缺少魔法咒语的哪一部分?

最佳答案

这里缺少两件事。首先,使用嵌入式eventstore客户端时,必须启动节点:

node.Start();

其次,您必须等待节点成为主节点才能使用连接。 ClusterVNode 有一个名为 NodeStatusChanged 的事件,您可以收听该事件并找出何时有主节点。以下应该有效:

ClusterVNode node = EmbeddedVNodeBuilder
    .AsSingleNode()
    .RunInMemory()
    .OnDefaultEndpoints()
    .Build();

bool isNodeMaster = false;
node.NodeStatusChanged += (sender, args) => {
    isNodeMaster = args.NewVNodeState == VNodeState.Master;
};
node.Start();

var stopwatch = new Stopwatch();
stopwatch.Start();
while (!isNodeMaster) {
    if (stopwatch.Elapsed.Seconds > 20) {
        throw new InvalidOperationException(
        "Waited too long (20 seconds) for EventStore node to become master.");
    }
    Thread.Sleep(1);
}
stopwatch.Stop();

var connection = EmbeddedEventStoreConnection.Create(node);
await connection.ConnectAsync();
var sampleEventData = new EventData(Guid.NewGuid(), "myTestEvent", false, new byte[] { 6, 10, 15 }, null);
WriteResult writeResult = await connection.AppendToStreamAsync("sampleStream, ExpectedVersion.NoStream, sampleEventData);

秒表的东西不是必需的,但有助于在出现问题并且节点永远不会成为主节点时跳出 while 循环。

如果您在事件处理程序委托(delegate)中放置一个断点,您会注意到 node 通过 3 个 VNodeState 进行处理。首先是 VNodeState.Unknown,然后是 VNodeState.PreMaster,最后是 VNodeState.Master

在创建连接并对其调用 ConnectAsync() 之前,您也不需要等待节点成为主节点。但是,您需要等待节点成为主节点,然后才能在其上调用任何其他方法,例如 AppendToStreamAsync 而不会遇到原始问题中的异常。

关于.net - EventStore嵌入式客户端如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611460/

相关文章:

events - CQRS/ES 架构上的补偿事件

eventstoredb - 无法从外部访问 Windows Azure 上的事件存储

c# - Debug|Trace.WriteLine 来自 Visual Studio 中的 C# 插件 - 通过 ConsoleTraceListener 显示

c# - 在 WPF 中使用 datatriggers 设置 ItemsSource 属性

c# - 如何解决 ASP.NET 中全局文件中的 Ninject 依赖项?

php - 准备好的语句的绑定(bind)参数中的第一个参数(?)/值(?)是什么?

java - 如何以编程方式(java 或 http)在 GetEventStore 中创建投影

.net - 使用 using 返回 IEnumerable

iPhone:在库文档中找不到 Sqlite 文件

php - 使用不同类型的用户在mySQL上创建角色