• c# redis密码验证笔记


    实现后的东西

     跳到H盘;cd打开指定文件夹

     执行命令:redis-server.exe redis.conf 

    这时候另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了。

    切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。

    设置键值对 set myKey abc

    取出键值对 get myKey

    然后设置密码

    获取密码 :127.0.0.1:6379> CONFIG get requirepas 

    设置密码:127.0.0.1:6379> CONFIG set requirepass "123"

    然后连接后,验证密码:127.0.0.1:6379> AUTH "123";然后才能进行操作

    结果如下:设置密码要重新验证:不然config get requirepass  找不到

     

     c# 中应用:添加引用 ServiceStack.Redis 3.9.x Complete Library;代码是复制的

    public class RedisCacheHelper
        {
            private static readonly PooledRedisClientManager pool = null;
            private static readonly string[] writeHosts = null;
            private static readonly string[] readHosts = null;
            public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
            public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
    
            static RedisCacheHelper()
            {
                var redisWriteHost = ConfigurationManager.AppSettings["redis_server_write"];
                var redisReadHost = ConfigurationManager.AppSettings["redis_server_read"];
                if (!string.IsNullOrEmpty(redisWriteHost))
                {
                    writeHosts = redisWriteHost.Split(',');
                    readHosts = redisReadHost.Split(',');
                    if (readHosts.Length > 0)
                    {
                        pool = new PooledRedisClientManager(writeHosts, readHosts,
                            new RedisClientManagerConfig()
                            {
                                MaxWritePoolSize = RedisMaxWritePool,
                                MaxReadPoolSize = RedisMaxReadPool,
    
                                AutoStart = true
                            });
                    }
                }
            }
            public static void Add<T>(string key, T value, DateTime expiry)
            {
                if (value == null)
                {
                    return;
                }
    
                if (expiry <= DateTime.Now)
                {
                    Remove(key);
                    return;
                }
    
                try
                {
                    if (pool != null)
                    {
                        using (var r = pool.GetClient())
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                r.Set(key, value, expiry - DateTime.Now);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
                }
    
            }
    
            public static void Add<T>(string key, T value)
            {
                RedisCacheHelper.Add<T>(key, value, DateTime.Now.AddMinutes(10));
            }
    
            public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
            {
                if (value == null)
                {
                    return;
                }
    
                if (slidingExpiration.TotalSeconds <= 0)
                {
                    Remove(key);
                    return;
                }
                try
                {
                    if (pool != null)
                    {
                        using (var r = pool.GetClient())
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                r.Set(key, value, slidingExpiration);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
                }
    
            }
    
            public static T Get<T>(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return default(T);
                }
                T obj = default(T);
                try
                {
                    if (pool != null)
                    {
                        using (var r = pool.GetClient())
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                obj = r.Get<T>(key);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
                }
                return obj;
            }
    
            public static void Remove(string key)
            {
                try
                {
                    if (pool != null)
                    {
                        using (var r = pool.GetClient())
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                r.Remove(key);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
                }
    
            }
    
            public static bool Exists(string key)
            {
                try
                {
                    if (pool != null)
                    {
                        using (var r = pool.GetClient())
                        {
                            if (r != null)
                            {
                                r.SendTimeout = 1000;
                                return r.ContainsKey(key);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
                }
    
                return false;
            }
    
            public static IDictionary<string, T> GetAll<T>(IEnumerable<string> keys) where T : class
            {
                if (keys == null)
                {
                    return null;
                }
                keys = keys.Where(k => !string.IsNullOrWhiteSpace(k));
    
                if (keys.Count() == 1)
                {
                    T obj = Get<T>(keys.Single());
    
                    if (obj != null)
                    {
                        return new Dictionary<string, T>() { { keys.Single(), obj } };
                    }
    
                    return null;
                }
                if (!keys.Any())
                {
                    return null;
                }
                try
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.GetAll<T>(keys);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", keys.Aggregate((a, b) => a + "," + b));
                }
                return null;
            }  
        }

    配置文件加了密码的设置

      源码是柘木写的:

    /// <summary>
             /// IP地址中可以加入auth验证   password@ip:port
             /// </summary>
             /// <param name="hosts"></param>
             /// <returns></returns>
            public static List<RedisEndpoint> ToRedisEndPoints(this IEnumerable<string> hosts)
             {
                 if (hosts == null) return new List<RedisEndpoint>();
                 //redis终结点的列表
                var redisEndpoints = new List<RedisEndpoint>();
                 foreach (var host in hosts)
               {
                    RedisEndpoint endpoint;
                     string[] hostParts;
                    if (host.Contains("@"))
                     {
                        hostParts = host.SplitOnLast('@');
                        var password = hostParts[0];
                       hostParts = hostParts[1].Split(':');
                        endpoint = GetRedisEndPoint(hostParts);
                         endpoint.Password = password;
                    }
                     else
                     {
                        hostParts = host.Split(':');
                         endpoint = GetRedisEndPoint(hostParts);
                   }
                    redisEndpoints.Add(endpoint);
                 }
                 return redisEndpoints;
            }
  • 相关阅读:
    iphone 越狱后 安装 pillow 报错 (未解决, 仅记录)
    阿甘正传影评
    聊聊“内卷”的本质
    Django REST Framework: 使用cach_page和drf-extensions进行缓存
    Python常用第三方库大全
    Go 第三方库推荐:类型转换如此简单
    Python 内置库:itertools
    4 款 MySQL 调优工具
    如何使用 asyncio 限制协程的并发数
    Go 的json 解析标准库竟然存在这样的陷阱?
  • 原文地址:https://www.cnblogs.com/weifeng123/p/16063522.html
Copyright © 2020-2023  润新知