public async Task <bool> SaveAsync <T>(T data, byte[] bytes, string uniqueId = null) where T : IEventBase <K> { var table = await tableInfo.GetTable(data.Timestamp); var saveSql = $"INSERT INTO {table.Name}(Id,stateid,msgid,typecode,data,version,iscomplete) VALUES(@Id,@StateId,@MsgId,@TypeCode,@Data,@Version,@IsComplete)"; data.Id = OGuid.GenerateNewId().ToString(); string msgId = uniqueId; if (string.IsNullOrEmpty(msgId)) { msgId = data.Id; } try { using (var conn = tableInfo.CreateConnection()) { await conn.ExecuteAsync(saveSql, new { data.Id, StateId = data.StateId.ToString(), MsgId = msgId, data.TypeCode, Data = bytes, Version = data.Version, IsComplete = false }); } return(true); } catch (Exception ex) { if (!(ex.InnerException is Npgsql.PostgresException e && e.SqlState == "23505")) { throw ex; } } return(false); }
public AmountTransferEvent(string toAccountId, decimal amount, decimal balance) { Id = OGuid.GenerateNewId().ToString(); ToAccountId = toAccountId; Amount = amount; Balance = balance; }
protected async ValueTask <bool> RaiseEvent(IEventBase <K> @event, string uniqueId = null, string hashKey = null) { try { State.IncrementDoingVersion();//标记将要处理的Version @event.Id = OGuid.GenerateNewId().ToString(); @event.StateId = GrainId; @event.Version = State.Version + 1; @event.Timestamp = DateTime.UtcNow; using (var ms = new PooledMemoryStream()) { GetSerializer().Serialize(ms, @event); var bytes = ms.ToArray(); var result = await GetEventStorage().SaveAsync(@event, bytes, uniqueId); if (result) { EventHandle.Apply(State, @event); if (SupportAsync) { //消息写入消息队列,以提供异步服务 await GetMQService().Publish(@event, bytes, string.IsNullOrEmpty(hashKey) ? GrainId.ToString() : hashKey); } State.UpdateVersion(@event);//更新处理完成的Version await SaveSnapshotAsync(); return(true); } else { State.DecrementDoingVersion();//还原doing Version } } } catch (Exception ex) { State.DecrementDoingVersion();//还原doing Version Logger.LogError(LogEventIds.EventRaiseError, ex, "Apply event {0} error, EventId={1}", @event.TypeCode, @event.Version); throw ex; } return(false); }
public AmountAddEvent(decimal amount, decimal balance) { Id = OGuid.GenerateNewId().ToString(); Amount = amount; Balance = balance; }