Redis安装及C#调用

一、Redis简介

             Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理。它支持字符串哈希表列表集合有序集合位图hyperloglogs等数据类型。内置复制、Lua脚本、LRU收回、事务以及不同级别磁盘持久化功能,同时通过Redis Sentinel提供高可用,通过Redis Cluster提供自动分区。sd 

Redis官网上相关安装、命令、配置等信息写的已经非常清楚(查看官网) 我就简单介绍下。

二、下载安装

            (1)下载

              Windows 环境生成好的文件下载地址下载地址 (这里版本比较老旧。你可以通过其他途径下载别人生成好的文件。这里有redis-2.8.17 ), 这里版本可能已经比较老旧,新版本可以自己下载源码生成github.com下载地址(msvs文件夹里有解决方案可以用Vs2013生成,这里需要更新到update5)。

            下载完文件解压目录如下:

             

    (2)安装:

     配置文件中几个比较常用配置文件

      1. port 6379   端口号  

                2. bind 127.0.0.1  IP   

                3. requirepass 访问的密码  

                4. maxheap 记得把这个配置节点打开,否者redis 服务无法启动。例如maxheap 1024000000(我自己用3.0.504测试时需要注释掉这个节点)  

                5. timeout:请求超时时间  

 

其他配置说明。配置文件中有比较清楚的英文描述。看不懂英文?。没关系。下载中有配中文描述。

配置好配置文件。直接点击startup.bat就可以了。这时你会看到如下

当你看到这个页面的时候说明。你的服务已经成功启动了。(这个页面不能关。关了服务就停止了)

如果没有一闪而没。可能你配置或在其他错误。我们就老老实实的输入cmd-》文件目录-》执行命令。根据日志找问题并解决问题

下面我们来做个存储测试。

另开个窗口(服务窗口不能关闭)

测试结果如下

客户端语句如下

           $ redis-cli -h host -p port -a password  

           如果需要做多台机器负载均衡只需要在另一台机器上配置信息
           # slaveof <masterip> <masterport> 这个节点配置上就可以了。

三、C#调用

1、下载相关dll

      

    2、常用方法整理

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.AddDays(1));  
    }  
  
    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;  
    }  
}  

  设置配置信息

 

       这时你就可以

       RedisCacheHelper.Add<string>(key, value);

       这样调用了。

 

原文地址:https://www.cnblogs.com/qukaicheng/p/7514168.html