Redis for C#

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

参考

StackExchange.Redis

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

虽然ServiceStack.Redis有15%的性能优势,但还是推荐使用: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();

StackExchange.Redis两个神器:ConnectionCountersIProfiler 

  • 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 

 

转载于:https://www.cnblogs.com/wjcx-sqh/p/11116619.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值