由于要做一个同一个页面上多种图表数据的下载,考虑到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. SNMP-配置文件详解

    当下的 SNMP 服务器通常用来被诸如 Nagios.Cacti.Zabbix 等监控软件收集数据,SNMP 的很多高级特性用的不是特别频繁.因而只需对 SNMP 进行一些简单.基础的配置以满足各种监 ...

  2. mysql 主从 重新同步

    mysql 主从同步一担出了问题之后,就会导致从库上的数据和主库不一样了.所以需要生新同步数据. 1.登录主库服务器,进入mysql,命令为:mysql -uroot -ppassword 2.执行: ...

  3. POI中getLastRowNum() 和getLastCellNum()的区别

    hssfSheet.getLastRowNum();//最后一行行标,比行数小1 hssfSheet.getRow(k).getLastCellNum();//获取列数,比最后一列列标大1

  4. 报错:Unable to load configuration. - action - file:/E:/apache-tomcat-8.0.37/webapps/20161102-struts2-3/WEB-INF/classes/struts.xml:11:73

    第一种报错: 严重: Exception starting filter struts2Unable to load configuration. - action - file:/E:/apache ...

  5. Delphi制作DLL

    一.开使你的第一个DLL专案 1.File->Close all->File->New﹝DLL﹞ 代码: //自动产生Code如下 library Project2; //这有段废话 ...

  6. webform 创建树

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI ...

  7. mysql日志详细解析

    MySQL日志: 主要包含:错误日志.查询日志.慢查询日志.事务日志.二进制日志: 日志是mysql数据库的重要组成部分.日志文件中记录着mysql数据库运行期间发生的变化:也就是说用来记录mysql ...

  8. switch语句

    应用条件语句可以很方便地使程序实现分支,但是出现分支比较多的时候,虽然可以用嵌套的if语句来解决,但是程序结构会显得复杂,甚至凌乱.为方便实现多情况选择,C++提供了一种switch开关语句.   一 ...

  9. 32. Path Sum && Path Sum II

    Path Sum OJ: https://oj.leetcode.com/problems/path-sum/ Given a binary tree and a sum, determine if ...

  10. Django views 中 View decorators

    decorators(装饰器) 1. require_http_methods 在django.views.decorators.http中,可以用来限制请求的权限. require_http_met ...