42 lines
1.4 KiB
C#
42 lines
1.4 KiB
C#
using MyCode.Project.Infrastructure.Cache;
|
||
using MyCode.Project.Infrastructure.Exceptions;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace MyCode.Project.Infrastructure.Common
|
||
{
|
||
public static class CacheHelper
|
||
{
|
||
#region GetCacheValue(得到缓存中的值)
|
||
/// <summary>
|
||
/// 得到缓存中的值,用法: CacheHelper.GetCacheValue<long>("id",() => IdHelper.GetNewId());
|
||
/// </summary>
|
||
/// <typeparam name="T">要返回的对象实体</typeparam>
|
||
/// <param name="cacheKey">缓存key</param>
|
||
/// <param name="func">执行的函数</param>
|
||
/// <param name="cacheSecond">多少秒,默认60</param>
|
||
/// <returns></returns>
|
||
public static T GetCacheValue<T>(string cacheKey,
|
||
Func<T> func,
|
||
int cacheSecond = 60)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(cacheKey)) { throw new BaseException("缓存key参数cacheKey不能为空"); }
|
||
|
||
var cache = new SystemCache();
|
||
|
||
//该Token已经存在缓存了
|
||
if (cache.Exists(cacheKey)) { return cache.Get<T>(cacheKey); }
|
||
|
||
var returnValue = func.Invoke();
|
||
|
||
if (returnValue != null) { cache.Set(cacheKey, returnValue, new TimeSpan(0, 0, cacheSecond)); }
|
||
|
||
return returnValue;
|
||
}
|
||
#endregion
|
||
}
|
||
}
|