我最近开始尝试.net-core ( nuget package )的EventStore Client API。但是,我正在努力将事件写入流中。下面是我用来建立连接的代码:
private readonly string _eventStoreName = "localhost";
private readonly string _eventStorePort = "1113";
protected IEventStoreConnection Connection;
public EventStoreTestFixture()
{
var eventStoreIpAddress = Dns.GetHostAddressesAsync(_eventStoreName).Result;
var ipAddress = GetIpAddressFromHost(eventStoreIpAddress);
var connectionSettings = ConnectionSettings.Create()
.SetDefaultUserCredentials(new UserCredentials("admin", "changeit"))
.EnableVerboseLogging();
Connection = EventStoreConnection.Create(connectionSettings,new IPEndPoint(ipAddress, int.Parse(_eventStorePort)));
Connection.ConnectAsync().Wait();
}
private static IPAddress GetIpAddressFromHost(IPAddress[] eventStoreIpAddress)
{
return
eventStoreIpAddress.FirstOrDefault(
ipAddress => ipAddress.AddressFamily.Equals(AddressFamily.InterNetwork));
}
这是我尝试写入 EventStream 的代码:
public class EmployeeEventSourcedRepository<T> where T : class, IEvenSourced
{
private readonly IEventStoreConnection _connection;
public EmployeeEventSourcedRepository(IEventStoreConnection connection)
{
_connection = connection;
}
public async Task SaveAsync(T eventSourced)
{
var eventsToSave =
eventSourced.PendingChanges
.Select(change => new EventData(Guid.NewGuid(),
change.GetType().Name,
true,
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(change, Formatting.None)),
new byte[]{}));
var streamId = $"{eventSourced.GetType().Name.ToLowerInvariant()}-{eventSourced.Id}";
await _connection.AppendToStreamAsync(streamId, ExpectedVersion.Any, eventsToSave);
}
}
IEventSourced
界面非常简单,如下所示:
public interface IEvenSourced
{
Guid Id { get; }
IEnumerable<Event> PendingChanges { get; }
}
现在,当我调用该SaveAsync
函数时,我经常遇到异常:EventStore.ClientAPI.Exceptions.ConnectionClosedException : Connection 'ES-9105371b-bf54-4e18-98e7-d67e4ce11aef' was closed
。
PS 我也尝试过使用 .net Client API,它似乎使用相同的代码工作得很好。
任何指针将不胜感激。干杯!