3

There seem to be no docs regarding how to set up, run, and connect to an Embedded EventStore client using the EventStore.Client.Embedded nuget package. With the following code:

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);

Everything seems to work fine up until the AppendToStreamAsync line, which throws the following exception:

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

What part of the magic incantation is missing to get around this exception?

4

1 回答 1

6

这里缺少两件事。首先,当使用嵌入式 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秒表的东西不是必需的,但有助于在出现问题并且节点永远不会成为主节点时跳出循环。

如果您在事件处理程序委托中放置断点,您会注意到node进度经过 3VNodeState秒。首先它将是VNodeState.Unknown,然后VNodeState.PreMaster,最后VNodeState.Master

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

于 2015-11-09T14:49:07.920 回答