Redis 是高性能鍵值存儲,廣泛用於緩存、會話、消息隊列。Windows 環境下部署較簡單,本文記錄完整安裝、配置及 C# 客端接入流程。
redis.conf 關鍵項# 綁定地址,生產環境請改為具體內網 IP,勿用 0.0.0.0
bind 127.0.0.1
port 6379
# 是否守護進程運行(Windows 下無效,通過服務管理)
# daemonize no
# 密碼認證(強烈建議設置)
requirepass YourStrongPassword123
# 持久化策略:AOF + RDB 混合
appendonly yes
appendfsync everysec
save 900 1
save 300 10
save 60 10000
# 最大內存與淘汰策略
maxmemory 512mb
maxmemory-policy allkeys-lru
管理員權限 CMD 執行:
cd /d D:\Redis
redis-server.exe redis.conf
新開窗口測試:
redis-cli.exe -a YourStrongPassword123
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> set testkey "hello redis"
OK
127.0.0.1:6379> get testkey
"hello redis"
redis-server.exe --service-install redis.conf --loglevel verbose
redis-server.exe --service-start
以後可通過 `services.msc` 或 `net start/stop Redis` 管理。
推薦使用 StackExchange.Redis(官方推薦、高性能、異步優先)。
Install-Package StackExchange.Redis
# 或 .NET CLI
dotnet add package StackExchange.Redis
using StackExchange.Redis;
using System;
public sealed class RedisHelper
{
private static readonly Lazy _lazyConnection =
new Lazy(() =>
{
var config = "127.0.0.1:6379,password=YourStrongPassword123,abortConnect=false,syncTimeout=5000";
return ConnectionMultiplexer.Connect(config);
});
public static ConnectionMultiplexer Connection => _lazyConnection.Value;
public static IDatabase Database => Connection.GetDatabase();
// 獲取 Server 對象用於管理操作
public static IServer Server => Connection.GetServer("127.0.0.1:6379");
}
ConnectionMultiplexer 線程安全,全應用僅需一個實例。abortConnect=false 允許啟動時 Redis 不可用,後台自動重連。
public class RedisService
{
private readonly IDatabase _db = RedisHelper.Database;
// String 操作
public bool SetString(string key, string value, TimeSpan? expiry = null)
=> _db.StringSet(key, value, expiry);
public string GetString(string key)
=> _db.StringGet(key);
// Hash 操作(適合對象存儲)
public void SetHash(string key, T obj) where T : class
{
var entries = ObjectToHashEntries(obj);
_db.HashSet(key, entries);
}
public T GetHash(string key) where T : class, new()
{
var entries = _db.HashGetAll(key);
if (entries.Length == 0) return null;
return HashEntriesToObject(entries);
}
// Key 管理
public bool KeyExists(string key) => _db.KeyExists(key);
public bool KeyDelete(string key) => _db.KeyDelete(key);
public TimeSpan? KeyTtl(string key) => _db.KeyTimeToLive(key);
// 輔助:對象 <-> HashEntry[] 轉換(簡易反射版,生產建議用 MessagePack/Protobuf)
private HashEntry[] ObjectToHashEntries(T obj)
{
var props = typeof(T).GetProperties();
var entries = new HashEntry[props.Length];
for (int i = 0; i < props.Length; i++)
{
var val = props[i].GetValue(obj);
entries[i] = new HashEntry(props[i].Name, val?.ToString() ?? "");
}
return entries;
}
private T HashEntriesToObject(HashEntry[] entries) where T : new()
{
var obj = new T();
var dict = entries.ToDictionary(e => e.Name.ToString(), e => e.Value.ToString());
foreach (var prop in typeof(T).GetProperties())
{
if (dict.TryGetValue(prop.Name, out var val))
{
prop.SetValue(obj, Convert.ChangeType(val, prop.PropertyType));
}
}
return obj;
}
}
public async Task GetStringAsync(string key)
{
return await _db.StringGetAsync(key);
}
public async Task SetStringAsync(string key, string value, TimeSpan? expiry = null)
{
return await _db.StringSetAsync(key, value, expiry);
}
ConnectionMultiplexer 內部維護連接池,默認最小/最大連接數可通過配置調整:`minPoolSize=10,maxPoolSize=100`。IBatch 或 CreateBatch() 打包命令,減少網絡往返:
var batch = _db.CreateBatch();
for (int i = 0; i < 1000; i++)
{
batch.StringSetAsync($"key{i}", $"value{i}");
}
batch.Execute(); // 一次性發送
// 訂閱
var sub = RedisHelper.Connection.GetSubscriber();
await sub.SubscribeAsync("channel:news", (channel, message) =>
{
Console.WriteLine($"收到消息: {message}");
});
// 發布
await sub.PublishAsync("channel:news", "Breaking News!");
var luaScript = @"
local current = redis.call('GET', KEYS[1])
if current == false then
redis.call('SET', KEYS[1], ARGV[1])
return 1
end
return 0
";
var script = LuaScript.Prepare(luaScript);
var result = await _db.ScriptEvaluateAsync(script, new { KEYS = new[] { "lock:key" }, ARGV = new[] { "lock_value" } });
bind 配置、密碼正確性、syncTimeout 設置。maxmemory-policy、大 Key 檢測(`redis-cli --bigkeys`)、未過期 Key 清理。Windows 下部署 Redis 推薦 Memurai 或社區版,配置密碼、持久化、內存策略並註冊服務。C# 端使用 StackExchange.Redis 單例連接,封裝異步 CRUD、Hash 對象映射、批量管道、發布訂閱與 Lua 腳本,即可構建高性能、可維護的緩存層。
