最近我开始尝试使用.net-core的EventStore客户端API(nuget包)。然而,我在将事件写入流中方面遇到了问题。以下是我用于建立连接的代码:
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));
}
以下是我尝试写入事件流的代码:
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:连接'ES-9105371b-bf54-4e18-98e7-d67e4ce11aef'已关闭
。附注:我也尝试使用.NET客户端API,相同的代码似乎可以正常工作。
如有任何指导,将不胜感激。干杯!