自己写了一个RedisHelper,现贴出来,希望各位大神能够指正和优化。

using System;
using StackExchange.Redis;
using System.Configuration; namespace Common.Redis
{
public static partial class RedisHelper
{
private static readonly string ConnectString = ConfigurationManager.ConnectionStrings["RedisConnection"].ToString();
private static Lazy<ConnectionMultiplexer> _lazyConnection;
private static readonly Object MultiplexerLock = new Object();
private static readonly IDatabase Cache; static RedisHelper()
{
var conn = CreateManager.Value;
Cache = conn.GetDatabase(); //获取实例
} private static Lazy<ConnectionMultiplexer> GetManager(string connectionString = null)
{
if (string.IsNullOrEmpty(connectionString))
{
connectionString = GetDefaultConnectionString();
} return new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(connectionString));
} private static Lazy<ConnectionMultiplexer> CreateManager
{
get
{
if (_lazyConnection == null)
{
lock (MultiplexerLock)
{
if (_lazyConnection != null) return _lazyConnection; _lazyConnection = GetManager();
return _lazyConnection;
}
} return _lazyConnection;
}
} public static string GetDefaultConnectionString()
{
return ConnectString;
}
}
}

使用patial 修饰符,由于Redis中的数据类型操作不少,所以把它们单独分到一个文件。核心的,可优化的主要还是上面的代码。


使用的是StackExchange.Redis Redis 客户端。

连接字符串从配置文件 application web.config读取。配置如下:

  <connectionStrings>
<add name="RedisConnection" connectionString="10.13.11.101:6379,10.13.18.191:6379,keepAlive=180,allowAdmin=True,$CLIENT=,$CLUSTER=,$CONFIG=,$ECHO=,$INFO=,$PING=" />
</connectionStrings>

由于Redis的高速读写的特性,密码是很容易被破解的,所以最好还是部署在内网环境中。

使用 Lazy<ConnectionMultiplexer> 而不是 ConnectionMultiplexer,是可以按需延迟加载。参考文件:

http://blog.sina.com.cn/s/blog_537517170102w3ib.html

真正的操作方法在下面:

using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Text;
using StackExchange.Redis; namespace Common.Redis
{
public partial class RedisHelper
{
public const string DefaultOrder = "desc"; #region Keys
public static bool KeyExists(string key)
{
var bResult = Cache.KeyExists(key);
return bResult;
} public static bool SetExpire(string key, DateTime datetime)
{
return Cache.KeyExpire(key, datetime);
} public static bool SetExpire(string key, int timeout = )
{
return Cache.KeyExpire(key, DateTime.Now.AddSeconds(timeout));
} public static bool Set<T>(string key, T t, int timeout = )
{
var value = JsonSerializer.SerializeToString(t);
bool bResult = Cache.StringSet(key, value);
if (timeout > )
{
Cache.KeyExpire(key, DateTime.Now.AddSeconds(timeout));
}
return bResult;
} public static bool KeyDelete(string key)
{
return Cache.KeyDelete(key);
} public static bool KeyRename(string oldKey, string newKey)
{
return Cache.KeyRename(oldKey, newKey);
}
#endregion #region Hashes
public static bool IsExist(string hashId, string key)
{
return Cache.HashExists(hashId, key);
} public static bool SetHash<T>(string hashId, string key, T t)
{
var value = JsonSerializer.SerializeToString(t);
return Cache.HashSet(hashId, key, value);
} public static bool Remove(string hashId, string key)
{
return Cache.HashDelete(hashId, key);
} public static long StringIncrement(string hashId, string key, long value = )
{
return Cache.HashIncrement(hashId, key, value);
} public static T Get<T>(string hashId, string key)
{
string value = Cache.HashGet(hashId, key);
return JsonSerializer.DeserializeFromString<T>(value);
} public static long GetHashCount(string hashId)
{
var length = Cache.HashLength(hashId);
return length;
} public static string Get(string hashId, string key)
{
string value = Cache.HashGet(hashId, key).ToString();
return value;
} public static List<T> GetAll<T>(string hashId)
{
var result = new List<T>();
var list = Cache.HashGetAll(hashId).ToList();
if (list.Count > )
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<T>(x.Value);
result.Add(value);
});
}
return result;
} public static List<string> GetAllFields(string hashId)
{
var result = new List<string>();
var list = Cache.HashKeys(hashId).ToList();
if (list.Count > )
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<string>(x);
result.Add(value);
});
}
return result;
}
#endregion #region Sorted Sets
public static bool SortedSetItemIsExist(string setId, string item)
{
var value = GetItemScoreFromSortedSet(setId, item);
if (value != null)
{
return true;
}
return false;
} public static bool SortedSetAdd(string setId, string item, double score, int timeout = )
{
return Cache.SortedSetAdd(setId, item, score);
} public static List<string> GetSortedSetRangeByRank(string setId, long fromRank, long toRank, string order = DefaultOrder)
{
var result = new List<string>();
var list = Cache.SortedSetRangeByRank(setId, fromRank, toRank, order == Order.Descending.ToString().ToLower() ? Order.Descending : Order.Ascending).ToList();
if (list.Any())
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<string>(x);
result.Add(value);
});
}
return result;
} public static Dictionary<string, double> GetSortedSetRangeByRankWithScores(string setId, long fromRank, long toRank, string order = DefaultOrder)
{
var result = new Dictionary<string, double>();
var list = Cache.SortedSetRangeByRankWithScores(setId, fromRank, toRank, order == Order.Descending.ToString().ToLower() ? Order.Descending : Order.Ascending).ToList();
if (list.Any())
{
list.ForEach(x =>
{
result.Add(x.Element, x.Score);
});
}
return result;
} public static List<string> GetSortedSetRangeByValue(string setId, long minValue, long maxValue)
{
var result = new List<string>();
var list = Cache.SortedSetRangeByValue(setId, minValue, maxValue).ToList();
if (list.Any())
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<string>(x);
result.Add(value);
});
}
return result;
} public static long GetSortedSetLength(string setId)
{
return Cache.SortedSetLength(setId);
} public static long GetSortedSetLength(string setId, double minValue, double maxValue)
{
return Cache.SortedSetLength(setId, minValue, maxValue);
} public static long? GetItemRankFromSortedSet(string setId, string item, string order = DefaultOrder)
{
return Cache.SortedSetRank(setId, item, order == Order.Descending.ToString().ToLower() ? Order.Descending : Order.Ascending);
} public static double? GetItemScoreFromSortedSet(string setId, string item)
{
return Cache.SortedSetScore(setId, item);
} public static double SetSortedSetItemIncrement(string setId, string item, double score = )
{
return Cache.SortedSetIncrement(setId, item, score);
} public static double SortedSetItemDecrement(string setId, string item, double score = -)
{
return Cache.SortedSetDecrement(setId, item, score);
} public static bool RemoveItemFromSortedSet(string setId, string item)
{
return Cache.SortedSetRemove(setId, item);
} public static long RemoveByRankFromSortedSet(string setId, long fromRank, long toRank)
{
return Cache.SortedSetRemoveRangeByRank(setId, fromRank, toRank);
} public static long RemoveByScoreFromSortedSet(string setId, double minValue, double maxValue)
{
return Cache.SortedSetRemoveRangeByScore(setId, minValue, maxValue);
} public static long RemoveByLexFromSortedSet(string setId, int minValue, int maxValue)
{
//TODO: Don't know its meaning
//return Cache.SortedSetRemoveRangeByValue(setId, minValue, maxValue);
return ;
}
#endregion #region Lists public static long AddList<T>(string listId, T t)
{
var value = JsonSerializer.SerializeToString(t);
return Cache.ListLeftPush(listId, value);
} public static List<T> GetList<T>(string listId, long start = , long stop = -)
{
var result = new List<T>();
var list = Cache.ListRange(listId, start, stop).ToList();
if (list.Count > )
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<T>(x);
result.Add(value);
});
}
return result;
}
#endregion #region Strings public static string Get(string key)
{
string value = Cache.StringGet(key);
return value;
} public static T StringGet<T>(string key)
{
string value = Cache.StringGet(key);
return JsonSerializer.DeserializeFromString<T>(value);
} public static double StringIncrement(string key, double value)
{
return Cache.StringIncrement(key, value);
} public static long StringAppend(string key, string value)
{
return Cache.StringAppend(value, value, CommandFlags.None);
}
#endregion
}
}

ILONEY

Redis 有五种常用数据类型,由于我实际中经常使用的是Hash,List,Sorted Set,String,故只我只贴出了上面我测试有限的方法出来,各位可自行补充。

最好自己新建一个文件,这样会比较符合开放-封闭 原则。

最后附上我为了学习Redis最常访问的站点:

Redis 官网:http://redis.io/

StackExchange.Redis 的github文档:

https://github.com/StackExchange/StackExchange.Redis

Stackoverflow 站点:

http://stackoverflow.com/search?q=Redis

RedisHelper in C#的更多相关文章

  1. Basic Tutorials of Redis(9) -First Edition RedisHelper

    After learning the basic opreation of Redis,we should take some time to summarize the usage. And I w ...

  2. C# Azure 存储-分布式缓存Redis工具类 RedisHelper

    using System; using System.Collections.Generic; using Newtonsoft.Json; using StackExchange.Redis; na ...

  3. Asp.Net Core 2.0 项目实战(6)Redis配置、封装帮助类RedisHelper及使用实例

    本文目录 1. 摘要 2. Redis配置 3. RedisHelper 4.使用实例 5. 总结 1.  摘要 由于內存存取速度远高于磁盘读取的特性,为了程序效率提高性能,通常会把常用的不常变动的数 ...

  4. [C#] 使用 StackExchange.Redis 封装属于自己的 RedisHelper

    使用 StackExchange.Redis 封装属于自己的 RedisHelper 目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List ...

  5. RedisHelper帮助类

    using Newtonsoft.Json; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using Stack ...

  6. 使用 StackExchange.Redis 封装属于自己的 RedisHelper

    目录 核心类 ConnectionMultiplexer 字符串(String) 哈希(Hash) 列表(List) 有序集合(sorted set) Key 操作 发布订阅 其他 简介 目前 .NE ...

  7. RedisHelper (C#)

    <add key="RedisServers" value="172.20.2.90:9379,password=Aa+123456789" /> ...

  8. RedisHelper Redis帮助类

    using StackExchange.Redis; using System; using System.Collections.Generic; using System.IO; using Sy ...

  9. Redis:RedisHelper(5)

    /// <summary> /// Redis 助手 /// </summary> public class RedisHelper { /// <summary> ...

随机推荐

  1. linux命令之awk

    简介 awk命令的名称是取自三位创始人Alfred Aho .Peter Weinberger 和 Brian Kernighan姓名的首字母,awk有自己的程序设计语言,设计简短的程序,读入文件,数 ...

  2. FPGA设计中的float

    在通常的设计中,不建议使用浮点数计算,因为浮点数计算会消耗FPGA大量的逻辑单元.但很多情况下,又需要使用浮点数进行计算提高精度. 所以需要有合适的方法计算浮点运算. 正常情况下FPGA只能以整形数据 ...

  3. 运维平台cmdb开发-day1

    序读项目由来 终极目标,运维平台.自动化.装机,监控,安装软件,部署基础服务,资产管理,之前是excel,现在是客户端自动获取,变更记录 后台管理 api 采集资产 四种模式agent 定时,每天执行 ...

  4. FastJSON使用笔记

    虽然使用FastJSON来生成JSON数据非常简单 最常用的的方法就是JSON.toJSONString()静态方法,这个方法参数可以给一个String,也可以是一个int,也可以给一个Object类 ...

  5. 【BZOJ】1833: [ZJOI2010] count 数字计数(数位dp)

    题目 传送门:QWQ 分析 蒟蒻不会数位dp,又是现学的 用$ dp[i][j][k] $ 表示表示长度为i开头j的所有数字中k的个数 然后预处理出这个数组,再计算答案 代码 #include < ...

  6. 示例文件下载demo

    页面: 后台: package com.js.ai.modules.shwindow.util; import java.io.BufferedInputStream; import java.io. ...

  7. Oracle段高水位(HWM, high water mark)问题

    Oracle对表做全表扫描的时候 ,会扫描完HWM以下的数据块.如果某个表delete(delete操作不会降低高水位)了大量数据,那么这时对表做全表扫描就会做很多无用功,扫描了一大堆数据块,最后发现 ...

  8. python学习笔记(十四): unittest

    Python中有一个自带的单元测试框架是unittest模块,用它来做单元测试,它里面封装好了一些校验返回的结果方法和一些用例执行前的初始化操作. 在说unittest之前,先说几个概念: TestC ...

  9. HTTP之URL

    URI 和 URL 与 URI(统一资源标识符)相比,我们更熟悉 URL(Uniform Resource Locator,统一资源定位符).URL 正是使用 Web 浏览器等访问 Web 页面时需要 ...

  10. JSP显示错误信息中四个范围来保存变量

    JSP中提供了四个范围来保存变量,分别是page,request,session,以及application 其中page范围只在当前页面有效,离开当前页面就失效了,这个肯定不行 request范围在 ...