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下載