46 lines
1.4 KiB
C#
46 lines
1.4 KiB
C#
using System;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
|
|
namespace FAuth.Extensions
|
|
{
|
|
/// <summary>
|
|
/// 使用微软Redis扩展方法组件实现Redis缓冲
|
|
/// </summary>
|
|
public class RedisCacheProvider:ICacheProvider
|
|
{
|
|
/// <summary>
|
|
/// 基础缓冲组件
|
|
/// </summary>
|
|
public IDistributedCache Cache { get; set; }
|
|
/// <summary>
|
|
/// 基础序列化组件
|
|
/// </summary>
|
|
public IJsonProvider Json { get; set; }
|
|
|
|
public RedisCacheProvider(IJsonProvider jsonProvider,IDistributedCache distributedCache = null) {
|
|
this.Cache = distributedCache;
|
|
this.Json = jsonProvider;
|
|
}
|
|
|
|
public T GetObj<T>(string key) where T : class, new() {
|
|
if(this.Cache == null) {
|
|
return null;
|
|
}
|
|
var str = this.Cache.GetString(key);
|
|
if(str.IsNullOrEmpty()) {
|
|
return null;
|
|
}
|
|
return this.Json.GetObj<T>(str);
|
|
}
|
|
|
|
public void SetCache<T>(string key,T obj,TimeSpan span) where T : class {
|
|
if(this.Cache == null || obj == null || span == null || span == TimeSpan.Zero) {
|
|
return;
|
|
}
|
|
this.Cache.SetString(key,this.Json.GetJson(obj),new DistributedCacheEntryOptions {
|
|
AbsoluteExpirationRelativeToNow = span,
|
|
});
|
|
}
|
|
}
|
|
}
|