public interface ICacheHelper
{
T Get<T>(string key);
void Set<T>(string key, T value);
void Remove(string key);
}
public User Get(int id)
{
if (id <= 0)
throw new ArgumentNullException("id");
var key = string.Format(USER_CACHE_KEY, id);
var user = _cacheHelper.Get<User>(key);
if (user != null)
return user;
return _repository.Get(id);
}
public User GetV2(int id)
{
if (id <= 0)
throw new ArgumentNullException("id");
var key = string.Format(USER_CACHE_KEY, id);
var user = _cacheHelper.Get<User>(key);
if (user != null)
return user;
user = _repository.Get(id);
if (user != null)
_cacheHelper.Set(key, user);
return user;
}
public User GetV3(int id)
{
if (id <= 0)
throw new ArgumentNullException("id");
var key = string.Format(USER_CACHE_KEY, id);
return _cacheHelperV2.Get<User>(key, () => _repository.Get(id));
}
//ICache Get<T>实现
public T Get<T>(string key, Func<T> fetch = null)
{
T result = default(T);
var obj = Cache.Get(key);
if (obj is T)
{
result = (T)obj;
}
if(result == null)
{
result = fetch();
if (result != null)
Set(key, result);
}
return result;
}
public T Get<T>(object id, Func<T> fetch = null)
{
var type = typeof(T);
var key = string.Format("urn:{1}:{2}", type.Name, id.ToString());//这里是关键,直接用TypeName来充当Key
return Get(key, fetch);
}
public T Get<T>(string key, Func<T> fetch = null)
{
T result = default(T);
var obj = Cache.Get(key);
if (obj is T)
{
result = (T)obj;
}
if (result == null)
{
result = fetch();
if (result != null)
Set(key, result);
}
return result;
}
public User GetV4(int id)
{
if (id <= 0)
throw new ArgumentNullException("id");
return _cacheHelperV3.Get<User>(id, () => _repository.Get(id));
}
public class User
{
[PrimaryKey] //这个Attribute是最重要的东西
public int UserId { get; set;}
public string UserName { get; set; }
public string Cellphone { get; set; }
}
public void Set<T>(T obj)
{
//此处应该被缓存以提高反射的效率
var type = typeof(T);
var primaryKey = type.GetProperties()
.FirstOrDefault(t => t.GetCustomAttributes(false)
.Any(c => c is PrimaryKeyAttribute));//这里通过取PrimaryKeyAttribute来获取ID的value
var keyValue = primaryKey.GetValue(obj, null);
var key = string.Format("urn:{0}:{1}", type.Name, keyValue);
var dt = DateTime.UtcNow.AddDays(1);//假设默认缓存1天
var offset = new DateTimeOffset(dt);
Cache.Set(key, obj, offset);
}
public class UserCacheEntity
{
[PrimaryKey]
public int ID
{
get
{
return string.Format("{0}:{1}", UserId, UserName);
}
}
public int UserId { get; set; }
public string UserName { get; set; }
public string Cellphone { get; set; }
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有