萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 連接 Redis 緩存數據庫:從安裝配置到實戰應用

Redis 簡介與 Windows 安裝

Redis 是高性能鍵值存儲,廣泛用於緩存、會話、消息隊列。Windows 環境下部署較簡單,本文記錄完整安裝、配置及 C# 客端接入流程。

1. 下載與安裝

  • 官方不再直接提供 Windows 二進制,推薦使用 Memurai(兼容 Redis 協議、免費開發版)或 tporadowski/redis 社區構建版。
  • 下載 ZIP 包(如 `redis-5.0.14.zip`),解壓至 `D:\Redis`。

2. 配置文件 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

3. 啟動與驗證

管理員權限 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"

4. 註冊為 Windows 服務(生產必備)


redis-server.exe --service-install redis.conf --loglevel verbose
redis-server.exe --service-start

以後可通過 `services.msc` 或 `net start/stop Redis` 管理。

C# 客戶端接入實戰

推薦使用 StackExchange.Redis(官方推薦、高性能、異步優先)。

1. NuGet 安裝

Install-Package StackExchange.Redis
# 或 .NET CLI
dotnet add package StackExchange.Redis

2. 連接複用最佳實踐(單例模式)


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 不可用,後台自動重連。

3. 基礎 CRUD 操作封裝


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;
    }
}

4. 異步調用示例(高併發必備)


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!");

Lua 腳本原子操作


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" } });

常見問題排查

  1. 連接超時:檢查防火牆、bind 配置、密碼正確性、syncTimeout 設置。
  2. 內存飆升:檢查 maxmemory-policy、大 Key 檢測(`redis-cli --bigkeys`)、未過期 Key 清理。
  3. 阻塞主線程:嚴禁在 UI 線程同步調用 Redis,全程使用 `Async` 後綴方法。

總結

Windows 下部署 Redis 推薦 Memurai 或社區版,配置密碼、持久化、內存策略並註冊服務。C# 端使用 StackExchange.Redis 單例連接,封裝異步 CRUD、Hash 對象映射、批量管道、發布訂閱與 Lua 腳本,即可構建高性能、可維護的緩存層。

Redis 安裝目錄文件
解壓後文件列表
啟動服務器界面
測試連接成功
copyright © 萬盛學電腦網 all rights reserved