在.Net中缓存序列化的Json字符串或MemoryCache中的实际对象引用是否更好?

时间:2018-05-18 17:06:29

标签: c# .net domain-driven-design snapshot event-sourcing

我有一个像这样的聚合快照缓存仓库:

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对序列进行序列化/反序列化以避免并发问题。 但是..我的问题是:

  1. 将对象实际克隆到anohter实例并将其作为实际对象进行缓存会更高效吗?
  2. 保持缓存对象的字符串表示是否有任何优势?因为实际上更容易序列化它而不是在每个DTO / POCO类中实现ICloneable。

0 个答案:

没有答案