Redis 使用之StackExchange.Redis
1》设置与连接StackExchange.Redis
public static ConnectionMultiplexer RedisConnection; public static IDatabase RedisCacheDb; protected void Session_Start(object sender, EventArgs s) { string RedisConn = ConfigurationManager.ConnectionStrings["RedisCache"].ConnectionString; if (!string.IsNullOrEmpty(RedisConn)) { if (RedisConnection == null || !RedisConnection.IsConnected) RedisConnection = ConnectionMultiplexer.Connect(RedisConn); RedisCacheDb = RedisConnection.GetDatabase(); } }
private static Lazy<ConfigurationOptions> configOptions = new Lazy<ConfigurationOptions>
(() => { var configOptions = new ConfigurationOptions(); configOptions.EndPoints.Add("localhost:6379"); configOptions.ClientName = "RedisName"; configOptions.ConnectTimeout = 100000; configOptions.SyncTimeout = 100000; return configOptions; }); private static ConnectionMultiplexer conn; private static ConnectionMultiplexer LeakyConn { get { if (conn == null || !conn.IsConnected) conn = ConnectionMultiplexer.Connect(configOptions.Value); return conn; } }
2》使用StackExchange.Redis
static void Main(string[] args) { IDatabase db = BaseDataRedis.LeakeyConn.GetDatabase(); string key = "String"; string value = "value"; db.KeyDelete(key); Console.WriteLine("Before the assignment:{0}", db.StringGet(key)); db.StringSet(key, value); Console.WriteLine("when a value assigned:{0}", db.StringGet(key)); string[] companies = new string[] { "Google", "Apple", "Amazon", "GFI", "Blizzard", "IBM" }; int[] companyScores = new int[] { 95, 15, 80, 0, 100, 56 }; key = "awesomecompanies"; db.KeyDelete(key); for (int i = 0; i < companies.Length; i++) { db.SortedSetAdd(key, companies[i], companyScores[i]); } RedisValue[] redisValue = db.Sort(key); for (int i = 0; i < redisValue.Length; i++) { Console.WriteLine("Redis Key:{0},companiesName:{1}", key, redisValue[i].ToString()); } Console.ReadKey(); }