ServiceStack.Redis

初识Redis时接触到的.Net-Redis组件是 ServiceStack.Redis,其V3系列的最新版本是:ServiceStack.Redis.3.9.29.0

ServiceStack.Common.dll
ServiceStack.Interfaces.dll
ServiceStack.Redis.dll
ServiceStack.Text.dll

RedisClient

public void Init();
public bool ContainsKey(string key);
public bool Remove(string key);
public void RemoveByPattern(string pattern);
public void RemoveByRegex(string pattern);
public IEnumerable<string> GetKeysByPattern(string pattern);
public List<string> SearchKeys(string pattern);
public List<string> GetAllKeys(); // 数据库内的所有键(慎用)
public string GetRandomKey();
public T Get<T>(string key);
public IRedisTypedClient<T> As<T>(); // /* 重要 */
public bool Add<T>(string key, T value [, DateTime expiresAt]); // [设置过期时间]
public bool Add<T>(string key, T value [, TimeSpan expiresIn]);
public bool Set<T>(string key, T value [, DateTime expiresAt]); // [设置过期时间]
public bool Set<T>(string key, T value [, TimeSpan expiresIn]);
public bool ExpireEntryAt(string key, DateTime expireAt); // 设置过期时间
public bool ExpireEntryIn(string key, TimeSpan expireIn);
public TimeSpan GetTimeToLive(string key); // TTL时间
public long DecrementValue(string key); // 减
public long DecrementValueBy(string key, int count);
public long IncrementValue(string key); // 增
public long IncrementValueBy(string key, int count);

支持类型

// string
public long GetStringCount(string key);
public string GetValue(string key);
public void SetValue(string key, string value [, TimeSpan expireIn]);
public void RenameKey(string fromName, string toName);
public int AppendToValue(string key, string value);
public string GetAndSetValue(string key, string value);
public string GetSubstring(string key, int fromIndex, int toIndex);
public List<string> GetValues(List<string> keys);
public Dictionary<string, string> GetValuesMap(List<string> keys); // List
public int GetListCount(string listId);
public int RemoveItemFromList(string listId, string value);
public string RemoveStart/End/AllFromList(string listId);
public void SetItemInList(string listId, int listIndex, string value);
public void AddItemToList(string listId, string value);
public void AddRangeToList(string listId, List<string> values);
public List<string> GetAllItemsFromList(string listId);
public string GetItemFromList(string listId, int listIndex);
public List<string> GetRangeFromList(string listId, int startingFrom, int endingAt);
public List<string> GetRangeFromSortedList(string listId, int startingFrom, int endingAt);
public List<string> GetSortedItemsFromList(string listId, SortOptions sortOptions);
public List<T> GetValues<T>(List<string> keys);
public Dictionary<string, T> GetValuesMap<T>(List<string> keys);
// List作为队列
public void EnqueueItemOnList(string listId, string value);
public string DequeueItemFromList(string listId);
// List作为栈
public void PushItemToList(string listId, string value);
public string PopItemFromList(string listId);
public string PopAndPushItemBetweenLists(string fromListId, string toListId); // Set
public int GetSetCount(string setId);
public bool SetContainsItem(string setId, string item);
public void RemoveItemFromSet(string setId, string item);
public void AddItemToSet(string setId, string item);
public void AddRangeToSet(string setId, List<string> items);
public HashSet<string> GetAllItemsFromSet(string setId);
public string GetRandomItemFromSet(string setId);
public List<string> GetSortedEntryValues(string setId, int startingFrom, int endingAt);
public HashSet<string> GetDifferencesFromSet(string fromSetId, params string[] withSetIds);
public HashSet<string> GetIntersectFromSets(params string[] setIds);
public HashSet<string> GetUnionFromSets(params string[] setIds);
public void StoreDifferencesFromSet(string intoSetId, string fromSetId, params string[] withSetIds);
public void StoreIntersectFromSets(string intoSetId, params string[] setIds);
public void StoreUnionFromSets(string intoSetId, params string[] setIds);
public void MoveBetweenSets(string fromSetId, string toSetId, string item);
public string PopItemFromSet(string setId);  // Hash
public int GetHashCount(string hashId);
public bool HashContainsEntry(string hashId, string key);
public bool RemoveEntryFromHash(string hashId, string key);
public bool SetEntryInHash(string hashId, string key, string value);
public List<string> GetHashKeys(string hashId);
public List<string> GetHashValues(string hashId);
public Dictionary<string, string> GetAllEntriesFromHash(string hashId);
public string GetValueFromHash(string hashId, string key);
public List<string> GetValuesFromHash(string hashId, params string[] keys);
public T GetFromHash<T>(object id); // SortedSet(zset)
public int GetSortedSetCount(string setId);
public bool SortedSetContainsItem(string setId, string value);
public bool RemoveItemFromSortedSet(string setId, string value);
public bool AddItemToSortedSet(string setId, string value [, double score]);
public bool AddRangeToSortedSet(string setId, List<string> values [, double score]);
public List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank);
public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank);
public List<string> GetAllItemsFromSortedSet[Desc](string setId);
public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId);

其中, public IRedisTypedClient<T> As<T>();  搭配接口 public interface IRedisTypedClient<T> : IEntityStore<T>{} 和 public interface IEntityStore<T>{}  中提供的方法可以完成各种操作。

在V3.0版本的基础上,其V4.0版本 ServiceStack.Redis-4.0.52 提供了更多的方法:

  • Scan方法;
  • 获取设置配置信息;
  • 支持Lua脚本; 
public RedisText Custom(params object[] cmdWithArgs);  // 执行命令
public RedisClient CloneClient();
public string GetClient();
public void SetClient(string name);
public void KillClient(string address);
public void ChangeDb(long db);
public DateTime GetServerTime();
public DateTime ConvertToServerDate(DateTime expiresAt);
public List<Dictionary<string, string>> GetClientsInfo();
public string GetConfig(string configItem);
public void SetConfig(string configItem, string value);
public void SaveConfig();
public void ResetInfoStats();

其中,Custom()方法可以执行绝大多数的Redis命令,ServiceStack.Redis.Commands定义命令,用于Custom()方法的第一个参数:

public static class Commands{
public static readonly byte[] CommandName;
}

由于ServiceStack.Redis的V4.0版本沦为商业用途,需充值否则限制:1)数据类型; 2)每小时访问次数6000

关于破解V4.0版本限制,参见:https://blog.csdn.net/hwt0101/article/details/80545383

虽然ServiceStack.Redis有15%的性能优势,但还是推荐使用:StackExchange.Redis 

StackExchange.Redis

StackExchange.Redis是专为.Net的Redis客户端API,被StackOverFlow、微软官方RedisSessionStateProvider也采用StackExchange.Redis实现。Cache组件 | 微软官方

RedisHelper.dll
StackExchange.Redis.dll

核心:ConnectionMultiplexer类(线程安全),在命名空间StackExchange.Redis中定义,封装Redis服务的操作细节,该类的实例被整个应用程序域共享和重用

ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redisClient .GetDatabase();

提供一个工具类参考

public class RedisUtils<T> where T : class
{
private readonly ConnectionMultiplexer redisConnect;
private readonly IDatabase db;
private readonly JilJsonUtil<T> _jilUtil; public RedisUtils(string connectionString)
{
_jilUtil = new JilJsonUtil<T>();
redisConnect = ConnectionMultiplexer.Connect(connectionString);
redisConnect.PreserveAsyncOrder = false;
db = redisConnect.GetDatabase();
} public string GetString(string _key)
{
return db.StringGet(_key);
}
public Dictionary<String, T> GetBatch(HashSet<String> keys)
{
Dictionary<String, T> res = new Dictionary<String, T>(); Dictionary<string, RedisValue> stringPipelineDic= GetStringPipelining(keys);
foreach (var key in stringPipelineDic.Keys)
{
var value = stringPipelineDic[key];
if (!value.IsNullOrEmpty)
{
res.Add(key, _jilUtil.Deserialize(value));
}
} return res;
} ///批量查询
private Dictionary<string, RedisValue> GetStringPipelining(HashSet<String> keys)
{
Dictionary<string, RedisValue> res = new Dictionary<string, RedisValue>(); Dictionary<string, Task<RedisValue>> tmp = new Dictionary<string, Task<RedisValue>>();
IBatch batch = db.CreateBatch();
foreach (var it in keys)
{
Task<RedisValue> stringGetAsync = batch.StringGetAsync(it);
tmp.Add(it, stringGetAsync);
}
batch.Execute(); foreach (var it in keys)
{
Task<RedisValue> stringGetAsync = tmp[it];
if (!stringGetAsync.Result.IsNullOrEmpty)
{
res.Add(it, stringGetAsync.Result);
}
} return res;
} ///存单个string的最大值是512M
public bool SetString(string key, string valStr, int seconds)
{
return db.StringSet(key, valStr, TimeSpan.FromSeconds(seconds));
}
public bool Set(string key, T value, int seconds)
{
var jsonStr = _jilUtil.Serialize(value);
return db.StringSet(key, jsonStr, TimeSpan.FromSeconds(seconds));
} ///PipeLine
public void SetBatch(Dictionary<string, T> dic, int seconds)
{
IBatch ibatch = db.CreateBatch();
foreach (var _key in dic.Keys)
{
T val = dic[_key];
ibatch.StringSetAsync(_key, _jilUtil.Serialize(val), TimeSpan.FromSeconds(seconds));
}
ibatch.Execute();
}
}

问题解决

[1]. 连接redis集群报错:(StackExchange.Redis.dll-v1.2.1)

StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s);
to create a disconnected multiplexer, disable AbortOnConnectFail. InternalFailure on PING
在 StackExchange.Redis.ConnectionMultiplexer.ConnectImpl(Func`1 multiplexerFactory, TextWriter log)
在 StackExchange.Redis.ConnectionMultiplexer.Connect(String configuration, TextWriter log)

原因:客户端dll版本与redis集群不兼容,替换为 v1.2.6 即可

管道(PipeLine)/批量(Batch)

  • 命令打包,降低通信往返时延

关于性能提升:参考1参考2

StackExchange.Redis两个神器:ConnectionCounters 和 IProfiler

  • ConnectionCounters:分析线程瞬时状态
  • IProfiler:跟踪一个请求总共执行redis命令及执行时长

对StackExchange.Redis的封装,参见:

但是,V1.0版本存在 timeout的问题,超时和异步慢的问题初探解决方法:

// 解决超时
ThreadPool.SetMinThreads(xx, xx);
// 解决异步慢
connection.PreserveAsyncOrder = false;

该问题在 StackExchange.Redis 2.0 中已解决,重构了异步队列,采用管道方式解决了异步慢的问题,参见:https://www.cnblogs.com/qhca/p/9347604.html

StackExchange.Redis二次封装 中,建议不要用lock作为单例使用,避免出现超时问题,待验证....

应用

Log4net+redis日志队列:https://www.cnblogs.com/dissun/p/10558817.html

Redis监控:由 Opserver工具  ==> RedisMonitor

基于 Redis的 Session共享

环境配置

.NET Framework 4.5 (推荐配置)
Microsoft.Web.RedisSessionStateProvider V2.2.6
StackExchange.Redis.StrongName V1.2.1 .NET Framework 4.6.1
RedisSessionProvider V1.2.8
StackExchange.Redis V2.0.6(貌似会报错,提示用低版本V1.2.6)

使用方法  

public static void RegistRedis()
{
StackExchange.Redis.ConfigurationOptions redisConfigOpts =
StackExchange.Redis.ConfigurationOptions.Parse("127.0.0.1:6379");
redisConfigOpts.Password = "********"; RedisSessionProvider.Config.RedisConnectionConfig.GetSERedisServerConfig =
(context) =>
{
return new KeyValuePair<string, StackExchange.Redis.ConfigurationOptions>(
"DefaultConnection", redisConfigOpts);
};
RedisSessionProvider.Config.RedisSessionConfig.SessionTimeout = TimeSpan.MaxValue;
}

CsRedis.Core

CsRedis 开源地址参见:https://github.com/2881099/csredis

/// .NET Framework 4.6
/// NuGet.Tools.vsix V2.12
/// CSRdeis.Core V3.0.62

CsRedis引入:https://www.cnblogs.com/kellynic/p/9803314.html

Redis for C#的更多相关文章

  1. 使用redis构建可靠分布式锁

    关于分布式锁的概念,具体实现方式,直接参阅下面两个帖子,这里就不多介绍了. 分布式锁的多种实现方式 分布式锁总结 对于分布式锁的几种实现方式的优劣,这里再列举下 1. 数据库实现方式 优点:易理解 缺 ...

  2. Ignite性能测试以及对redis的对比

    测试方法 为了对Ignite做一个基本了解,做了一个性能测试,测试方法也比较简单主要是针对client模式,因为这种方法和使用redis的方式特别像.测试方法很简单主要是下面几点: 不作参数优化,默认 ...

  3. mac osx 安装redis扩展

    1 php -v查看php版本 2 brew search php|grep redis 搜索对应的redis   ps:如果没有brew 就根据http://brew.sh安装 3 brew ins ...

  4. Redis/HBase/Tair比较

    KV系统对比表 对比维度 Redis Redis Cluster Medis Hbase Tair 访问模式    支持Value大小 理论上不超过1GB(建议不超过1MB) 理论上可配置(默认配置1 ...

  5. Redis数据库

    Redis是k-v型数据库的典范,设计思想及数据结构实现都值得学习. 1.数据类型 value支持五种数据类型:1.字符串(strings)2.字符串列表(lists)3.字符串集合(sets)4.有 ...

  6. redis 学习笔记(2)

    redis-cluster 简介 redis-cluster是一个分布式.容错的redis实现,redis-cluster通过将各个单独的redis实例通过特定的协议连接到一起实现了分布式.集群化的目 ...

  7. redis 学习笔记(1)

    redis持久化 snapshot数据快照(rdb) 这是一种定时将redis内存中的数据写入磁盘文件的一种方案,这样保留这一时刻redis中的数据镜像,用于意外回滚.redis的snapshot的格 ...

  8. python+uwsgi导致redis无法长链接引起性能下降问题记录

    今天在部署python代码到预生产环境时,web站老是出现redis链接未初始化,无法连接到服务的提示,比对了一下开发环境与测试环境代码,完全一致,然后就是查看各种日志,排查了半天也没有查明是什么原因 ...

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

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

  10. windows+nginx+iis+redis+Task.MainForm构建分布式架构 之 (nginx+iis构建服务集群)

    本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,由标题就能看出此内容不是一篇分享文章能说完的,所以我打算分几篇分享文章来讲解,一步一步实现分 ...

随机推荐

  1. Laya的调试,调试面板,断点调试

    参考: 性能统计面板介绍 版本2.1.1.1 调试面板 Laya有两个调试选项,编辑模式F9. 第一个调试模式,除了调试面板,还有一个查看当前舞台对象的面板.类似白鹭的Egret Inspector. ...

  2. Django中的QuerySet查询优化之prefetch_related

    转载的,做个笔记,原文链接 在数据库有外键的时候,使用 select_related() 和 prefetch_related() 可以很好的减少数据库请求的次数,从而提高性能.本文通过一个简单的例子 ...

  3. WINDOWS配置WSUS。

    wsus的注册表文件! Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINESOFTWAREPoliciesMicrosoftWindows ...

  4. 【linux学习笔记一】目录处理命令

    一 建立目录:mkdir make directories //创建一个name的目录 mkdir name //-p 递归创建 //在没有目录a也没有目录b的情况下 直接创建 mkdir -p a/ ...

  5. H5微信场景应用 audio模块

    css .bgAudio{width:27px;height:27px;position:fixed;right:10px;top:10px;z-index:999;-webkit-tap-highl ...

  6. 13点睛Spring4.1-Spring EL

    13.1 Spring EL Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似jsp的EL表达式语言; 本教程关注于在注解中使用Spring EL; Spring EL ...

  7. IDEA springboot maven 引用第三方jar包

    1.在左侧项目里新建一个 lib 文件夹,把第三方jar 包复制进去 . 2.修改pom.xml ,dependencies配置节增加,plugins 配置节做修改. dependencies配置节增 ...

  8. 模型-视图-控制器的C++解释

    模型-视图-控制器 (MVC) 并非一种技术,而是软件设计/工程的一个概念.MVC包含三个组成部分,如下图所示 模型 模型直接响应对数据的处理,比如数据库.模型不应依赖其它组成部分,即视图或控制器,换 ...

  9. 将自己的项目作为jar包发布到maven中央仓库

    maven版本是3.5.0,jdk是1.8(注意,不是说项目是1.8就行,必须是环境变量里的也是,不能超过1.8,否则一大堆问题,执行mvn前用javac -version看下版本) 一:先在sona ...

  10. 【转】那些年用过的Redis集群架构(含面试解析)

    引言 今天是2019年2月12号,也就是大年初八,我接到了高中同学刘有码面试失利的消息. 他面试的时候,身份是某知名公司的小码农一枚,却因为不懂自己生产上Redis是如何部署的,导致面试失败! 人间惨 ...