82870034 发表于 2017-7-1 15:30:22

第一次正式小用Redis存储

  由于要做一个同一个页面上多种图表数据的下载,考虑到Azure上面的session很不稳定(可用Redis provider存储session,较稳定),故决定改为Azure支持的Redis,顺便也学习一下这种新的存储方式。
  关于Redis的介绍这里不赘述了,他可存储多种类型的数据,不过还是相当基本的那些数据类型。
  开始的设计是,利用Redis的Hashs存储每一个数据表的行列信息。在写了一系列代码后,发现这样的话执行速度上会有很大的影响。
  后来经同事提醒,可以将table转换为json再进行Redis的String类型的存储。
  在Azure门户上进行相应的Redis的配置。
  然后先建立一个RedisClient类



1public class RedisClient
2   {      
3         private static readonly ILogger _logger = LoggerFactory.GetLogger(LoggerSourceName);
4         private const string LoggerSourceName = "RedisClient";
5
6         private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() =>
7         {
8             _logger.Info(LoggerSourceName, "Begin to create Redis connection");
9
10             //read connection information from storage/configuration-redis/Redis.config
11             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Config.CloudStorageAccount);
12             CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("configuration-redis");
13             if (!container.Exists())
14               throw new ConfigurationErrorsException("fail to get redis connection string");
15             CloudBlockBlob blob = container.GetBlockBlobReference("Redis.config");
16             if (!blob.Exists())
17               throw new ConfigurationErrorsException("fail to get redis connection string");
18             string redisConnectionString;
19             using (var ms = new MemoryStream())
20             {
21               blob.DownloadToStream(ms);
22               ms.Position = 0;
23               using (var sr = new StreamReader(ms))
24               {
25                     redisConnectionString = sr.ReadToEnd();
26               }
27             }
28
29
30             ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisConnectionString);
31             redis.ConfigurationChanged += redis_ConfigurationChanged;
32             redis.ConfigurationChangedBroadcast += redis_ConfigurationChangedBroadcast;
33             redis.ConnectionFailed += redis_ConnectionFailed;
34             redis.ConnectionRestored += redis_ConnectionRestored;
35             return redis;
36         });
37
38
39         private static IDatabase _db;
40
41         public static ConnectionMultiplexer Connection
42         {
43             get { return LazyConnection.Value; }
44         }
45
46         public static IDatabase Db
47         {
48             get { return _db ?? (_db = Connection.GetDatabase()); }
49         }
50
51
52         private static void redis_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
53         {
54             _logger.Info(LoggerSourceName, "Redis ConnectionRestored");
55         }
56
57         private static void redis_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
58         {
59             _logger.Info(LoggerSourceName, "Redis ConnectionFailed");
60         }
61
62         private static void redis_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
63         {
64             _logger.Info(LoggerSourceName, "Redis ConfigurationChangedBroadcast");
65         }
66
67         private static void redis_ConfigurationChanged(object sender, EndPointEventArgs e)
68         {
69             _logger.Info(LoggerSourceName, "Redis ConfigurationChanged");
70         }
71   }
  然后就是简单的写入啦。



public static void SetRedisTable(string key, DataTable dt)
{
if (dt != null && !string.IsNullOrEmpty(key))
{
string value = JsonHelper.ToJson(dt);
RedisClient.Db.StringSetAsync(key, value);
}      
}
  还有读取。



public static DataTable GetRedisTable(string key)
{
DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(key))
{
string s = RedisClient.Db.StringGet(key).ToString();
if (!string.IsNullOrEmpty(s))
dt = JsonHelper.JsonToDataTable(s);
}
return dt;
}
  以上很简单
  另有一段代码还不知道干嘛用,先记录下来。



1 public static class StackExchangeExtesion
2   {
3         public static T Get<T>(this IDatabase cache, string key)
4         {
5             var cachedValue = cache.StringGet(key);
6             if (String.IsNullOrEmpty(cachedValue))
7               return default(T);
8             return JsonConvert.DeserializeObject<T>(cachedValue);
9         }
10
11         public static object Get(this IDatabase cache, string key)
12         {
13             var cachedValue = cache.StringGet(key);
14             if (String.IsNullOrEmpty(cachedValue))
15               return null;
16             return JsonConvert.DeserializeObject<object>(cachedValue);
17         }
18
19         public static void Set(this IDatabase cache, string key, object value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
20         {
21             cache.StringSet(key, JsonConvert.SerializeObject(value), expiry, when, flags);
22         }
23
24         public static void ListPush(this IDatabase cache, string key, object value)
25         {
26             cache.ListRightPush(key, JsonConvert.SerializeObject(value));
27         }
28
29         public static RedisValue[] ListRange(this IDatabase cache, string key, long start, long stop)
30         {
31             if (start >= cache.ListLength(key))
32               return new RedisValue;
33
34             return cache.ListRange(key, start, stop);
35         }
36   }
页: [1]
查看完整版本: 第一次正式小用Redis存储