MongoDBCacheProvider 推送代码实现
namespace RG3.PF.Caching.MongoDB
{
/// <summary>
/// MongoDBCacheProvider 缓存实现类
/// </summary>
public partial class MongoDBCacheProvider
{
public async Task<T> GetJsonAsync<T>(string tableName, string key)
{
IMongoCollection<BsonDocument> _mongoCollection = _mogoDataBase.GetCollection<BsonDocument>(tableName);
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = Builders<BsonDocument>.Filter;
var item = filter.Eq("_id", key);
var doc = (await _mongoCollection.FindAsync(item))?.FirstOrDefault();
if (doc == null) return default(T);
return BsonSerializer.Deserialize<T>(doc);
}
public async Task<bool> SetJsonAsync<T>(string tableName, string key, T value, TimeSpan expiresIn, bool isSliding = false)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
IMongoCollection<BsonDocument> _mongoCollection = _mogoDataBase.GetCollection<BsonDocument>(tableName);
BsonDocument bsDoc = BsonSerializer.Deserialize<BsonDocument>(JsonUtil.Serialize(value, false, false, false));
bsDoc["_id"] = key;
bsDoc["_date"] = DateTime.Now;
try
{
var filter = Builders<BsonDocument>.Filter;
var item = filter.Eq("_id", key);
var doc = (await _mongoCollection.FindAsync(item))?.FirstOrDefault();
if (doc == null)
{
await _mongoCollection.InsertOneAsync(bsDoc);
}
else
{
await _mongoCollection.ReplaceOneAsync(item, bsDoc);
}
}
catch (Exception e)
{
//避免key并发插入导致的错误
Console.WriteLine($"【error】【MongoDBCacheProvider$Json】【{DateTime.Now.ToString()}】{e.Message}");
}
return true;
}
}
}
文档更新时间: 2023-05-22 11:19 作者:admin