獲取redis連接
public class RedisHelper { private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnection"].ConnectionString; private static ConnectionMultiplexer _connection; private static ConnectionMultiplexer Connection { get { if (_connection == null || !_connection.IsConnected) { _connection = ConnectionMultiplexer.Connect(ConnectionString); } return _connection; } } public static IDatabase GetDatabase() { ConnectionMultiplexer redis = Connection; //return redis.GetDatabase(RedisDatebaseId); return redis.GetDatabase(); } }
//根據模糊查詢條件獲取key值集合
var pattern = "UserInfoHash:*";//匹配符 var redisResult = db.ScriptEvaluate(LuaScript.Prepare( //Redis的keys模糊查詢: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = pattern }); string[] preSult = (string[])redisResult;//將返回的結果集轉為數組
//根據key值集合獲取所有Hash
var list = new List<ICustomInfo>();//定義存放客戶信息的集合 string json = "{ 'UserInfoHash:0', 'UserInfoHash:1','UserInfoHash:2', 'UserInfoHash:4' }"; //Redis的keys模糊查詢: " local result={} local mykeys=" + json + "; " + " for i,v in pairs(mykeys) do result[i]=redis.call('hgetall',v) end; " + " return result")); //將結果集轉為數組 var vals = (StackExchange.Redis.RedisResult[])redisResult1; foreach (var val in vals) { string[] preval = (string[])val; int indexCount = Array.IndexOf(preval, "CustomerCode"); int indexPwd = Array.IndexOf(preval, "Password"); string ac = preval[indexCount + 1];//賬號的值,等於賬號名稱所在的下標+1 list.Add(new CustomInfo() { Password = preval[indexPwd + 1], Account = ac, UpdateTime = DateTime.Now, Token = StringExtension.ToBase64String(string.Format("{0}:{1}", DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), ac)) }); }
注:根據key模糊查詢一次數據過多時,可能會報超時問題。 解決方法:在redis連接字符串加入對應的 syncTimeout=10000(發送/接收超時設置(毫秒) )