using StackExchange.Redis; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace DSWeb.Helper { public static class RedisHelper { /// /// 根据当前web.config配置,向redis写入值 /// public static void Set(string key, string content, int expireSeconds = 120) { ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisServerAddr"]); var strDbIdx = ConfigurationManager.AppSettings["RedisServerDB"]; var dbIdx = string.IsNullOrEmpty(strDbIdx) ? -1 : Convert.ToInt32(strDbIdx); IDatabase db = redis.GetDatabase(dbIdx); db.StringSet(key, content, expiry: new TimeSpan(0, 0, expireSeconds)); redis.Close(); } /// /// 根据当前web.config配置,从redis读取值 /// /// public static string Get(string key) { ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisServerAddr"]); var strDbIdx = ConfigurationManager.AppSettings["RedisServerDB"]; var dbIdx = string.IsNullOrEmpty(strDbIdx) ? -1 : Convert.ToInt32(strDbIdx); IDatabase db = redis.GetDatabase(dbIdx); string val = null; if (db.KeyExists(key)) { val = db.StringGet(key); } redis.Close(); return val; } } }