由于要做一个同一个页面上多种图表数据的下载,考虑到Azure上面的session很不稳定(可用Redis provider存储session,较稳定),故决定改为Azure支持的Redis,顺便也学习一下这种新的存储方式。

关于Redis的介绍这里不赘述了,他可存储多种类型的数据,不过还是相当基本的那些数据类型。

开始的设计是,利用Redis的Hashs存储每一个数据表的行列信息。在写了一系列代码后,发现这样的话执行速度上会有很大的影响。

后来经同事提醒,可以将table转换为json再进行Redis的String类型的存储。

在Azure门户上进行相应的Redis的配置。

然后先建立一个RedisClient类

  public class RedisClient
{
private static readonly ILogger _logger = LoggerFactory.GetLogger(LoggerSourceName);
private const string LoggerSourceName = "RedisClient"; private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
_logger.Info(LoggerSourceName, "Begin to create Redis connection"); //read connection information from storage/configuration-redis/Redis.config
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Config.CloudStorageAccount);
CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("configuration-redis");
if (!container.Exists())
throw new ConfigurationErrorsException("fail to get redis connection string");
CloudBlockBlob blob = container.GetBlockBlobReference("Redis.config");
if (!blob.Exists())
throw new ConfigurationErrorsException("fail to get redis connection string");
string redisConnectionString;
using (var ms = new MemoryStream())
{
blob.DownloadToStream(ms);
ms.Position = ;
using (var sr = new StreamReader(ms))
{
redisConnectionString = sr.ReadToEnd();
}
} ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(redisConnectionString);
redis.ConfigurationChanged += redis_ConfigurationChanged;
redis.ConfigurationChangedBroadcast += redis_ConfigurationChangedBroadcast;
redis.ConnectionFailed += redis_ConnectionFailed;
redis.ConnectionRestored += redis_ConnectionRestored;
return redis;
}); private static IDatabase _db; public static ConnectionMultiplexer Connection
{
get { return LazyConnection.Value; }
} public static IDatabase Db
{
get { return _db ?? (_db = Connection.GetDatabase()); }
} private static void redis_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
_logger.Info(LoggerSourceName, "Redis ConnectionRestored");
} private static void redis_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
_logger.Info(LoggerSourceName, "Redis ConnectionFailed");
} private static void redis_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
{
_logger.Info(LoggerSourceName, "Redis ConfigurationChangedBroadcast");
} private static void redis_ConfigurationChanged(object sender, EndPointEventArgs e)
{
_logger.Info(LoggerSourceName, "Redis ConfigurationChanged");
}
}

然后就是简单的写入啦。

 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;
}

以上很简单

另有一段代码还不知道干嘛用,先记录下来。

 public static class StackExchangeExtesion
{
public static T Get<T>(this IDatabase cache, string key)
{
var cachedValue = cache.StringGet(key);
if (String.IsNullOrEmpty(cachedValue))
return default(T);
return JsonConvert.DeserializeObject<T>(cachedValue);
} public static object Get(this IDatabase cache, string key)
{
var cachedValue = cache.StringGet(key);
if (String.IsNullOrEmpty(cachedValue))
return null;
return JsonConvert.DeserializeObject<object>(cachedValue);
} public static void Set(this IDatabase cache, string key, object value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
{
cache.StringSet(key, JsonConvert.SerializeObject(value), expiry, when, flags);
} public static void ListPush(this IDatabase cache, string key, object value)
{
cache.ListRightPush(key, JsonConvert.SerializeObject(value));
} public static RedisValue[] ListRange(this IDatabase cache, string key, long start, long stop)
{
if (start >= cache.ListLength(key))
return new RedisValue[]; return cache.ListRange(key, start, stop);
}
}

第一次正式小用Redis存储的更多相关文章

  1. nginx+iis+redis+Task.MainForm构建分布式架构 之 (redis存储分布式共享的session及共享session运作流程)

    本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,上一篇分享文章制作是在windows上使用的nginx,一般正式发布的时候是在linux来配 ...

  2. Asp.net Core 使用Redis存储Session

    前言 Asp.net Core 改变了之前的封闭,现在开源且开放,下面我们来用Redis存储Session来做一个简单的测试,或者叫做中间件(middleware). 对于Session来说褒贬不一, ...

  3. Redis存储Session

    net Core 使用Redis存储Session   前言 Asp.net Core 改变了之前的封闭,现在开源且开放,下面我们来用Redis存储Session来做一个简单的测试,或者叫做中间件(m ...

  4. 几分钟搞定redis存储session共享——设计实现

    前面我们写过C#在redis中存储常用的5种数据类型demo,没看过的可以点击电梯直达:https://www.cnblogs.com/xiongze520/p/10267804.html 我们上一篇 ...

  5. redis 存储java对象 两种方式

    根据redis的存储原理,Redis的key和value都支持二进制安全的字符串 1.利用序列化和反序列化的方式存储java对象我们可以通过对象的序列化与反序列化完成存储于取出,这样就可以使用redi ...

  6. [转]Asp.net Core 使用Redis存储Session

    本文转自:http://www.cnblogs.com/hantianwei/p/5723959.html 前言 Asp.net Core 改变了之前的封闭,现在开源且开放,下面我们来用Redis存储 ...

  7. Redis 存储机制

    Redis存储机制分成两种Snapshot和AOF.无论是那种机制,Redis都是将数据存储在内存中. Snapshot工作原理: 是将数据先存储在内存,然后当数据累计达到某些设定的伐值的时候,就会触 ...

  8. Redis 存储字符串和对象

    今天用redis存储,发现客户端jedis提供的存储方法中存储的类型只有String和byte数据,没有能够存储对象的,网上发现可以序列化存储对象.这就开始了我第一次序列化之旅.     1 测试类 ...

  9. springboot项目中的普通Session和使用redis存储session

    普通session: session store type使用来存放session的存储方式,目前Spring boot中只支持Redis方式, 由于本应用暂无需将session放入redis的需求, ...

随机推荐

  1. unity, 播放循环背景音乐注意事项

    循环背景音乐用wav格式,不要用mp3. 参考:http://answers.unity3d.com/questions/343057/how-do-i-make-unity-seamlessly-l ...

  2. 入口点函数的19种消息,AcRxArxApp只处理16种。

    AcRx::AppMsgCode一共有19种消息. 但由IMPLEMENT_ARX_ENTRYPOINT宏实现的App类,只处理了16种消息. 缺: kSuspendMsg = 16,    kIni ...

  3. CSS3 旋转代码备忘

    .Aclose { -webkit-transition-property: all; -webkit-transition-duration: .3s; -moz-transition-proper ...

  4. 原生+jquery 实现好看滚动条。

    //原生 <!doctype html> <html> <head> <meta charset="utf-8"> <titl ...

  5. 黄聪:wkhtmltopdf解决分页问题

    wkhtmltopdf 有个很好的方法,就是在那个div的样式后添加一个:page-break-inside:avoid;就ok了. <!DOCTYPE html PUBLIC "-/ ...

  6. java 线程的堵塞

    //线程的阻塞 // //线程 class xc1 implements Runnable{ public void run(){ for(int i=1;i<=30;i++){ System. ...

  7. (转)无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。此操作失败的原因是对 IID 为“{00020970-

    HRESULT:0x80030002 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft ...

  8. X5 内核浏览器对json格式支持的一个小区别

    var json1 = { "data": [{ "type": "pic", "filename": "P6 ...

  9. 如何调试IIS错误信息

    原文链接: http://blogs.msdn.com/b/tess/archive/2009/03/20/debugging-a-net-crash-with-rules-in-debug-diag ...

  10. 使用eclipse搭建hadoop开发环境

    下载一个 hadoop-eclipse-plugin-*.jar的eclipse插件,并放在plugins目录下 重启eclipse   打开视象,找“大象” 连接HDFS   success 编程准 ...