gpt4 book ai didi

c# - BsonDocument 到动态表达式或结果的内存缓存

转载 作者:IT老高 更新时间:2023-10-28 13:29:54 28 4
gpt4 key购买 nike

我正在尝试为 IMongoCollection 编写代理类这样我就可以为一些方法实现使用内存缓存。然而,问题是几乎所有的过滤器都是 FilterDefinition<T> 类型。这意味着我们可以调用Render在他们身上得到一个BsonDocument .我想知道是否有办法转换过滤器BsonDocument动态表达式,以便我可以在内存中运行它 List<T> .或者也许有更好的方法来做我不知道的内存缓存。谢谢。

更新:

我很想按照@simon-mourier 的建议编写一个解决方案,但这个 hacky 解决方案的问题是 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;
}
}
}

最佳答案

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

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

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

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

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> 上编写通用代理要简单得多。它只需要您专注于应用程序的特定需求。

关于c# - BsonDocument 到动态表达式或结果的内存缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151689/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com