你的位置:首页 > ASP.net教程

[ASP.net教程]C#Redis安装与使用


Redis是一个用的比较广泛的Key/Value的内存数据库,也是最快的key-value分布式缓存之一。

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

Redis快速入门教程:http://www.yiibai.com/redis/redis_quick_guide.html

解压版下载地址:https://github.com/dmajkic/redis/downloads

安装版下载地址:https://github.com/rgl/redis/downloads

ServiceStack.Redis:https://github.com/ServiceStack/ServiceStack.Redis

参考:

http://www.cnblogs.com/zhangweizhong/p/4969240.html

http://blog.csdn.net/qiujialongjjj/article/details/16945569

一、Redis安装

选择一个版本进行下载,压缩包中包括32位和64位的安装工具,或者直接使用安装版的进行安装,都是一样的,这里使用的是安装版的,安装结果如图:

 

安装完后会在系统服务中出现一个Redis Server的系统服务。

redis-server.exe:服务器的daemon启动程序。

redis.conf:配置文件。

redis-cli.exe:命令行客户端。

redis-check-dump.exe:本地数据库检查

redis-check-aof.exe:更新日志检查

redis-benchmark.exe:性能测试工具,测试Redis在你的系统及你的配置下的读写性能。

二、Redis配置

1. port 端口号,例如6379

2. bind 实例绑定的访问地址127.0.0.1

3. requirepass 访问的密码

4. maxheap 记得把这个配置节点打开,否者redis 服务无法启动。例如maxheap 1024000000

5. timeout:请求超时时间

6. logfile:log文件位置

7. databases:开启数据库的数量

8. dbfilename:数据快照文件名(只是文件名,不包括目录)

三、Redis使用

在Redis的安装目录下找到redis-cli.exe文件,双击启动它:

测试OK,至此Redis安装到此结束了,接下来是在C#中的实际运用。

 

二、Redis实战

1.建立项目,引用ServiceStack.Redis相关的四个类库。

2.配置文件

  <!-- redis Start  -->  <add key="SessionExpireMinutes" value="180" />  <add key="redis_server_session" value="127.0.0.1:6379" />  <add key="redis_max_read_pool" value="3" />  <add key="redis_max_write_pool" value="1" />  <!--redis end-->

3.创建一个Redis操作的公用类RedisCacheHelper

using ServiceStack.Redis;using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication{  class RedisCacheHelper  {    private static readonly PooledRedisClientManager pool = null;    private static readonly string[] redisHosts = 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 redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];      if (!string.IsNullOrEmpty(redisHostStr))      {        redisHosts = redisHostStr.Split(',');        if (redisHosts.Length > 0)        {          pool = new PooledRedisClientManager(redisHosts, redisHosts,            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, 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;    }  }}

View Code

4.程序测试

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication{  class Program  {    static void Main(string[] args)    {      Console.WriteLine("Redis写入缓存:");      RedisCacheHelper.Add("name1", "test1", DateTime.Now.AddDays(1));      Console.WriteLine("Redis获取缓存:");      string str = RedisCacheHelper.Get<string>("name1");      Console.WriteLine(str);      Console.ReadKey();    }  }}

View Code

5.输入结果

Demo下载