我有一个像这样的聚合快照缓存仓库:
using Eventing.Core.Domain;
using Eventing.Core.Serialization;
using Microsoft.Extensions.Caching.Memory;
using System;
namespace Eventing.Core.Persistence
{
public class InMemorySnapshotClient : ISnapshotClient
{
private readonly MemoryCache cache;
private readonly TimeSpan timeToLive;
private readonly IJsonSerializer serializer;
public InMemorySnapshotClient(IJsonSerializer serializer)
: this(TimeSpan.FromMinutes(30), serializer)
{ }
public InMemorySnapshotClient(TimeSpan timeToLive, IJsonSerializer serializer)
{
Ensure.NotNull(serializer, nameof(serializer));
this.cache = new MemoryCache(new MemoryCacheOptions());
this.timeToLive = timeToLive;
this.serializer = serializer;
}
public void Cache(IEventSourced state)
{
// make a copy of the state values to avoid concurrency problems with reusing references.
var serialized = this.serializer.Serialize(state);
this.cache.Set(
key: state.StreamName,
value: serialized,
absoluteExpiration: DateTimeOffset.UtcNow.Add(this.timeToLive));
}
public bool TryGet(string streamName, out IEventSourced state)
{
var serialized = this.cache.Get(streamName);
if (serialized == null)
{
state = null;
return false;
}
state = this.serializer.Deserialize<IEventSourced>((string)serialized);
return true;
}
}
}
请耐心等待,感谢您花时间阅读代码。正如您所看到的,我使用JSON.net对序列进行序列化/反序列化以避免并发问题。 但是..我的问题是: