工厂创建类:

public class CacheFactory
{
private static ICache cache = null;

private static readonly object lockHelper = new object();

public static ICache Cache
{
get
{
if (cache == null)
{
lock (lockHelper)
{
if (cache == null)
{
switch (CacheProvider)
{
case "Redis":cache = new RedisCacheImp(); break;
default:
case "Memory":cache = new MemoryCacheImp();break;
}
}
}
}
return cache;
}
}

public static string CacheProvider { get; set; } = "Redis";
}

  接口:

public interface ICache
{
bool SetCache<T>(string key, T value, DateTime? expireTime = null);

T GetCache<T>(string key);

bool RemoveCache(string key);

#region Hash
int SetHashFieldCache<T>(string key, string fieldKey, T fieldValue);

int SetHashFieldCache<T>(string key, Dictionary<string, T> dict);

T GetHashFieldCache<T>(string key, string fieldKey);

Dictionary<string, T> GetHashFieldCache<T>(string key, Dictionary<string, T> dict);

Dictionary<string, T> GetHashCache<T>(string key);

List<T> GetHashToListCache<T>(string key);

bool RemoveHashFieldCache(string key, string fieldKey);

Dictionary<string, bool> RemoveHashFieldCache(string key, Dictionary<string, bool> dict);
#endregion
}

  RedisCacheImp

public class RedisCacheImp : ICache
{
private IDatabase cache;
private ConnectionMultiplexer connection;

public RedisCacheImp()
{
connection = ConnectionMultiplexer.Connect(RedisConnectionString);
cache = connection.GetDatabase();
}


public bool SetCache<T>(string key, T value, DateTime? expireTime = null)
{
try
{
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string strValue = JsonConvert.SerializeObject(value, jsonOption);
if (string.IsNullOrEmpty(strValue)) return false;

if (expireTime == null) return cache.StringSet(key, strValue);
else return cache.StringSet(key, strValue, (expireTime.Value - DateTime.Now));

}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return false;
}

public bool RemoveCache(string key)
{
return cache.KeyDelete(key);
}

public T GetCache<T>(string key)
{
var t = default(T);
try
{
var value = cache.StringGet(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return t;
}

#region Hash
public int SetHashFieldCache<T>(string key, string fieldKey, T fieldValue)
{
return SetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, fieldValue } });
}

public int SetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
int count = 0;
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
foreach (string fieldKey in dict.Keys)
{
string fieldValue = JsonConvert.SerializeObject(dict[fieldKey], jsonOption);
count += cache.HashSet(key, fieldKey, fieldValue) ? 1 : 0;
}
return count;
}

public T GetHashFieldCache<T>(string key, string fieldKey)
{
var dict = GetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, default(T) } });
return dict[fieldKey];
}

public Dictionary<string, T> GetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
foreach (string fieldKey in dict.Keys)
{
string fieldValue = cache.HashGet(key, fieldKey);
dict[fieldKey] = JsonConvert.DeserializeObject<T>(fieldValue);
}
return dict;
}

public Dictionary<string, T> GetHashCache<T>(string key)
{
Dictionary<string, T> dict = new Dictionary<string, T>();
var hashFields = cache.HashGetAll(key);
foreach (HashEntry field in hashFields)
{
dict[field.Name] = JsonConvert.DeserializeObject<T>(field.Value);
}
return dict;
}

public List<T> GetHashToListCache<T>(string key)
{
List<T> list = new List<T>();
var hashFields = cache.HashGetAll(key);
foreach (HashEntry field in hashFields)
{
list.Add(JsonConvert.DeserializeObject<T>(field.Value));
}
return list;
}

public bool RemoveHashFieldCache(string key, string fieldKey)
{
Dictionary<string, bool> dict = new Dictionary<string, bool> { { fieldKey, false } };
dict = RemoveHashFieldCache(key, dict);
return dict[fieldKey];
}

public Dictionary<string, bool> RemoveHashFieldCache(string key, Dictionary<string, bool> dict)
{
foreach (string fieldKey in dict.Keys)
{
dict[fieldKey] = cache.HashDelete(key, fieldKey);
}
return dict;
}
#endregion

public void Dispose()
{
if (connection != null)
{
connection.Close();
}
GC.SuppressFinalize(this);
}
public string RedisConnectionString { get; set; }
}

  MemoryCacheImp

public class MemoryCacheImp : ICache
{
public static IServiceProvider ServiceProvider { get; set; }
private IMemoryCache cache = ServiceProvider.GetService<IMemoryCache>();

public bool SetCache<T>(string key, T value, DateTime? expireTime = null)
{
try
{
if (expireTime == null) return cache.Set<T>(key, value) != null;
return cache.Set(key, value, (expireTime.Value - DateTime.Now)) != null;
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return false;
}

public bool RemoveCache(string key)
{
cache.Remove(key);
return true;
}

public T GetCache<T>(string key)
{
var value = cache.Get<T>(key);
return value;
}

#region Hash
public int SetHashFieldCache<T>(string key, string fieldKey, T fieldValue)
{
return SetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, fieldValue } });
}

public int SetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
int count = 0;
foreach (string fieldKey in dict.Keys)
{
count += cache.Set(key, dict) != null ? 1 : 0;
}
return count;
}
public T GetHashFieldCache<T>(string key, string fieldKey)
{
var dict = GetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, default(T) } });
return dict[fieldKey];
}
public Dictionary<string, T> GetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
var hashFields = cache.Get<Dictionary<string, T>>(key);
foreach (KeyValuePair<string, T> keyValuePair in hashFields.Where(p => dict.Keys.Contains(p.Key)))
{
dict[keyValuePair.Key] = keyValuePair.Value;
}
return dict;
}

public Dictionary<string, T> GetHashCache<T>(string key)
{
Dictionary<string, T> dict = new Dictionary<string, T>();
var hashFields = cache.Get<Dictionary<string, T>>(key);
foreach (string field in hashFields.Keys)
{
dict[field] = hashFields[field];
}
return dict;
}

public List<T> GetHashToListCache<T>(string key)
{
List<T> list = new List<T>();
var hashFields = cache.Get<Dictionary<string, T>>(key);
foreach (string field in hashFields.Keys)
{
list.Add(hashFields[field]);
}
return list;
}

public bool RemoveHashFieldCache(string key, string fieldKey)
{
Dictionary<string, bool> dict = new Dictionary<string, bool> { { fieldKey, false } };
dict = RemoveHashFieldCache(key, dict);
return dict[fieldKey];
}

public Dictionary<string, bool> RemoveHashFieldCache(string key, Dictionary<string, bool> dict)
{
var hashFields = cache.Get<Dictionary<string, object>>(key);
foreach (string fieldKey in dict.Keys)
{
dict[fieldKey] = hashFields.Remove(fieldKey);
}
return dict;
}
#endregion
}

  日志记录:

public class LogHelper
{
private static readonly Logger log = LogManager.GetLogger(string.Empty);

public static void Trace(object msg, Exception ex = null)
{
if (ex == null)
{
log.Trace(msg.ParseToString());
}
else
{
log.Trace(msg + GetExceptionMessage(ex));
}
}

public static void Debug(object msg, Exception ex = null)
{
if (ex == null)
{
log.Debug(msg.ParseToString());
}
else
{
log.Debug(msg + GetExceptionMessage(ex));
}
}

public static void Info(object msg, Exception ex = null)
{
if (ex == null)
{
log.Info(msg.ParseToString());
}
else
{
log.Info(msg + GetExceptionMessage(ex));
}
}

public static void Warn(object msg, Exception ex = null)
{
if (ex == null)
{
log.Warn(msg.ParseToString());
}
else
{
log.Warn(msg + GetExceptionMessage(ex));
}
}

public static void Error(object msg, Exception ex = null)
{
if (ex == null)
{
log.Error(msg.ParseToString());
}
else
{
log.Error(msg + GetExceptionMessage(ex));
}
}

public static void Error(Exception ex)
{
if (ex != null)
{
log.Error(GetExceptionMessage(ex));
}
}

public static void Fatal(object msg, Exception ex = null)
{
if (ex == null)
{
log.Fatal(msg.ParseToString());
}
else
{
log.Fatal(msg + GetExceptionMessage(ex));
}
}

public static void Fatal(Exception ex)
{
if (ex != null)
{
log.Fatal(GetExceptionMessage(ex));
}
}

private static string GetExceptionMessage(Exception ex)
{
string message = string.Empty;
if (ex != null)
{
message += ex.Message;
message += Environment.NewLine;
Exception originalException = ex.GetOriginalException();
if (originalException != null)
{
if (originalException.Message != ex.Message)
{
message += originalException.Message;
message += Environment.NewLine;
}
}
message += ex.StackTrace;
message += Environment.NewLine;
}
return message;
}
}
public static partial class Extensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;

return ex.InnerException.GetOriginalException();
}

public static string ParseToString(this object obj)
{
try
{
if (obj == null)
return string.Empty;
else
return obj.ToString();
}
catch
{
return string.Empty;
}
}
}