BsonDocument到结果的动态表达或内存缓存

时间:2019-03-13 21:48:10

标签: c# mongodb mongodb-.net-driver

我正在尝试为IMongoCollection编写代理类,以便可以将内存缓存用于某些方法实现。但是,问题在于,几乎所有过滤器的类型均为FilterDefinition<T>,这意味着我们可以在它们上调用Render以获得BsonDocument。我想知道是否有一种方法可以将过滤器BsonDocument转换为动态Expression,以便可以对内存List<T>运行它。或者,也许还有一种我不知道的更好的内存缓存方法。谢谢。

更新:

我很想按照@ simon-mourier的建议编写解决方案,但是这个棘手的解决方案的问题是C#mongo驱动程序返回IAsyncCursor<T>进行查找操作,这基本上是BsonDocument s的流,并且每次读取后,它指向最后一个索引并自行处理。而且无法将流重置为其初始位置。这意味着下面的代码第一次起作用,但是之后,我们得到了一个例外,即游标位于流的末尾并且已经被处理。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DAL.Extensions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;

namespace DAL.Proxies
{
    public static class MongoCollectionProxy
    {
        private static readonly Dictionary<Type, object> _instances = new Dictionary<Type, object>();

        public static IMongoCollection<T> New<T>(IMongoCollection<T> proxy)
        {
            return ((IMongoCollection<T>)_instances.AddOrUpdate(typeof(T), () => new MongoCollectionBaseProxyImpl<T>(proxy)));
        }
    }

    public class MongoCollectionBaseProxyImpl<T> : MongoCollectionBase<T>
    {
        private readonly IMongoCollection<T> _proxy;

        private readonly ConcurrentDictionary<string, object> _cache = new ConcurrentDictionary<string, object>();

        public MongoCollectionBaseProxyImpl(IMongoCollection<T> proxy)
        {
            _proxy = proxy;
        }

        public override Task<IAsyncCursor<TResult>> AggregateAsync<TResult>(PipelineDefinition<T, TResult> pipeline,
            AggregateOptions options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return _proxy.AggregateAsync(pipeline, options, cancellationToken);
        }

        public override Task<BulkWriteResult<T>> BulkWriteAsync(IEnumerable<WriteModel<T>> requests,
            BulkWriteOptions options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return _proxy.BulkWriteAsync(requests, options, cancellationToken);
        }

        [Obsolete("Use CountDocumentsAsync or EstimatedDocumentCountAsync instead.")]
        public override Task<long> CountAsync(FilterDefinition<T> filter, CountOptions options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return _proxy.CountAsync(filter, options, cancellationToken);
        }

        public override Task<IAsyncCursor<TField>> DistinctAsync<TField>(FieldDefinition<T, TField> field,
            FilterDefinition<T> filter, DistinctOptions options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return _proxy.DistinctAsync(field, filter, options, cancellationToken);
        }

        public override async Task<IAsyncCursor<TProjection>> FindAsync<TProjection>(FilterDefinition<T> filter,
            FindOptions<T, TProjection> options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            // ReSharper disable once SpecifyACultureInStringConversionExplicitly
            return await CacheResult(filter.Render().ToString(), () => _proxy.FindAsync(filter, options, cancellationToken));
        }

        public override async Task<TProjection> FindOneAndDeleteAsync<TProjection>(FilterDefinition<T> filter,
            FindOneAndDeleteOptions<T, TProjection> options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return await InvalidateCache(_proxy.FindOneAndDeleteAsync(filter, options, cancellationToken));
        }

        public override async Task<TProjection> FindOneAndReplaceAsync<TProjection>(FilterDefinition<T> filter,
            T replacement,
            FindOneAndReplaceOptions<T, TProjection> options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return await InvalidateCache(_proxy.FindOneAndReplaceAsync(filter, replacement, options,
                cancellationToken));
        }

        public override async Task<TProjection> FindOneAndUpdateAsync<TProjection>(FilterDefinition<T> filter,
            UpdateDefinition<T> update,
            FindOneAndUpdateOptions<T, TProjection> options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return await InvalidateCache(_proxy.FindOneAndUpdateAsync(filter, update, options, cancellationToken));
        }

        public override Task<IAsyncCursor<TResult>> MapReduceAsync<TResult>(BsonJavaScript map, BsonJavaScript reduce,
            MapReduceOptions<T, TResult> options = null,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return _proxy.MapReduceAsync(map, reduce, options, cancellationToken);
        }

        public override IFilteredMongoCollection<TDerivedDocument> OfType<TDerivedDocument>()
        {
            return _proxy.OfType<TDerivedDocument>();
        }

        public override IMongoCollection<T> WithReadPreference(ReadPreference readPreference)
        {
            return _proxy.WithReadPreference(readPreference);
        }

        public override IMongoCollection<T> WithWriteConcern(WriteConcern writeConcern)
        {
            return _proxy.WithWriteConcern(writeConcern);
        }

        public override CollectionNamespace CollectionNamespace => _proxy.CollectionNamespace;

        public override IMongoDatabase Database => _proxy.Database;

        public override IBsonSerializer<T> DocumentSerializer => _proxy.DocumentSerializer;

        public override IMongoIndexManager<T> Indexes => _proxy.Indexes;

        public override MongoCollectionSettings Settings => _proxy.Settings;

        private async Task<TResult> CacheResult<TResult>(string key, Func<Task<TResult>> result)
        {
            return _cache.ContainsKey(key) ? (TResult) _cache[key] : (TResult) _cache.AddOrUpdate(key, await result());
        }

        private TResult InvalidateCache<TResult>(TResult result)
        {
            _cache.Clear();

            return result;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您唯一关心的是创建一个应用某种缓存策略的装饰器类,以避免某些数据库访问,那么我认为您应该尝试一种更简单的方法来解决问题。

我并不是说试图为接口IMongoCollection<T>编写装​​饰器本身是错误的,我只是说这不是解决问题的最简单方法。

更好的方法可能是将精力集中在应用程序的特定需求上。在下面的段落中,我将尝试解释我的观点。

让我们假设您的应用程序必须经常访问User集合,并且用户数据不会经常更改,因此它们是简单缓存策略的良好候选者。此时,您可以决定定义一个类似IUserRepository的抽象,并根据您的应用程序的需要来塑造该抽象。例如,考虑以下接口定义:

public interface IUserRepository 
{
  User GetById(Guid userId);
  ReadOnlyCollection<User> GetAll();
}

这时,您将编写一个使用MongoDB作为持久层的具体实现:

public class MongoUserRepository: IUserRepository 
{
  private readonly IMongoCollection<User> userCollection;

  public MongoUserRepository(IMongoCollection<User> userCollection)
  {
    this.userCollection = userCollection ?? throw new ArgumentNullException(nameof(userCollection));
  }

  // interface members implementation omitted for simplicity
}

然后,您应该为实现缓存方面的IUserRepository定义一个装饰器,如下所示:

public class UserRepositoryCachingDecorator: IUserRepository 
{
  private readonly IUserRepository decoratee;
  private readonly IMemoryCache cache;

  public UserRepositoryCachingDecorator(IUserRepository decoratee, IMemoryCache cache)
  {
    this.decoratee = decoratee ?? throw new ArgumentNullException(nameof(decoratee));
    this.cache = cache ?? throw new ArgumentNullException(nameof(cache));
  }

  // interface members implementation omitted for simplicity
}

我认为这是一种更好的方法,因为它比尝试在IMongoCollection<T>上编写通用代理要简单得多,并且只需要您专注于应用程序的特定需求即可。