本文轉自:http://www.cnblogs.com/gossip/p/4898653.htmlhtml
<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"); } }