/// <summary> /// 分布式缓存 /// </summary> public static class RedisCache { /// <summary> /// 单例工厂,每次初始化redis客户端从工厂中获取 /// </summary> private static IRedisClientFactory _factory = RedisCacheClientFactory.Instance; /// <summary> /// 设置redis缓存 /// </summary> /// <typeparam name="T">泛型类</typeparam> /// <param name="key">缓存键</param> /// <param name="value">泛型实体</param> /// <param name="expire">过期时间</param> /// <returns></returns> public static bool Set<T>(string key, T value, DateTime expire) { try { using (var client = GetClient()) { return client.Set<T>(key, value, expire); } } catch { return false; } } /// <summary> /// 获取缓存 /// </summary> /// <typeparam name="T">实体</typeparam> /// <param name="key">键值</param> /// <returns></returns> public static T Get<T>(string key) { try { using (var client = GetClient()) { return client.Get<T>(key); } } catch { //如果redis出现异常,则直接返回默认值 return default(T); } } /// <summary> /// 移除缓存 /// </summary> /// <param name="key"></param> public static void Remove(string key) { try { using (var client = GetClient()) { client.Remove(key); } } catch { } } public static void RemoveAll() { try { using (var client = GetClient()) { var keys = client.GetAllKeys(); client.RemoveAll(keys); } } catch { } } /// <summary> /// 获取客户端 /// </summary> /// <returns></returns> private static IRedisClient GetClient() { RedisClient client = null; if (string.IsNullOrEmpty(ConfigManager.RedisServer)) { throw new ArgumentNullException("redis server ip is empty."); } if (string.IsNullOrEmpty(ConfigManager.RedisPwd)) { throw new ArgumentNullException("redis server pwd is empty."); } client = _factory.CreateRedisClient(ConfigManager.RedisServer, ConfigManager.RedisPort); client.Password = ConfigManager.RedisPwd; client.Db = ConfigManager.RedisServerDb; return client; } }
用到的程序集
功能描述
可以直接缓存实体类,设置过期时间,移除缓存,获取缓存功能。
使用RedisClientFactory工厂获取redis客户端实例。如果Redis设置了密码,在配置文件中添加修改
client = factory.CreateRedisClient(ConfigManager.RedisServer, ConfigManager.RedisPort);
client.Password = ConfigManager.RedisPwd;
修改redis的ip和端口号,密码即可。
使用场景
具体的使用过程中,使用redis的超时可以对数据进行一些持久化管理,对于一些数据一致性不高的数据进行缓存,使得读取速度提高,使用redis集群时可以是用主从复制功能,Redis集群没有中心节点,并且带有复制和故障转移特性,这可以避免单个节点成为性能瓶颈,或者因为某个节点下线而导致整个集群下线。