标签:
<appSettings> <!--Redis写入服务器地址,可以添加多个服务器通过,分隔--> <add key="ReadWriteHosts" value="192.168.1.100:6379" /> <!--Redis读服务器地址,可以添加多个服务器通过,分隔--> <add key="ReadOnlyHosts" value="192.168.1.100:6380,127.0.0.1:6379" /> </appSettings>
class RedisConfig { public static RedisClient Redis { get { return (RedisClient)reidsPools.GetClient(); } } private static string[] hosts; private static PooledRedisClientManager reidsPools; static RedisConfig() { var readWriteHosts = ConfigurationManager.AppSettings["ReadWriteHosts"].Split(‘,‘); var readOnlyHosts = ConfigurationManager.AppSettings["ReadOnlyHosts"].Split(‘,‘); reidsPools = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 100,//“写”链接池链接数 MaxReadPoolSize = 200,//“读”链接池链接数 AutoStart = true, DefaultDb = 0 }); } }
public class RedisHelper { /// <summary> /// 获取值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T Get<T>(string key) { using (var redis = RedisConfig.Redis) { return redis.Get<T>(key); } } /// <summary> /// 设置值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool Set<T>(string key, T value) { using (var redis = RedisConfig.Redis) { return redis.Set<T>(key, value); } } /// <summary> /// 设置值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public bool Set<T>(string key, T value, DateTime dt) { using (var redis = RedisConfig.Redis) { return redis.Set<T>(key, value, dt); } } }
class Program { static void Main(string[] args) { var redis = new RedisHelper(); redis.Set<string>("aa", DateTime.Now.ToString()); var d = redis.Get<string>("aa"); } }