StackExchange.Redis 使用LuaScript脚本模糊查询hash

获取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();//定义存放客户信息的集合
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(发送/接收超时设置(毫秒) )

 

转载于:https://www.cnblogs.com/-xyl/p/11245104.html

你可能感兴趣的:(StackExchange.Redis 使用LuaScript脚本模糊查询hash)