在.NET项目中实现Redis缓存读写,最常用的客户端是StackExchange.Redis,它是一个高性能、稳定的Redis客户端库,支持多种Redis操作场景,适合大多数.NET应用的缓存需求。

环境准备
首先需要安装StackExchange.Redis的NuGet包,在Visual Studio的包管理器控制台执行以下命令即可完成安装:
Install-Package StackExchange.Redis
建立Redis连接
使用StackExchange.Redis操作Redis前,需要先创建连接对象,建议将连接对象做成单例,避免频繁创建连接带来的性能损耗。以下是创建连接的示例代码:
using StackExchange.Redis;
using System;
public class RedisHelper
{
// Redis连接字符串,根据实际部署的Redis地址修改
private static readonly string RedisConnectionString = "127.0.0.1:6379,password=";
private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect(RedisConnectionString);
});
// 获取Redis连接实例的单例
public static ConnectionMultiplexer Connection
{
get
{
return LazyConnection.Value;
}
}
// 获取数据库实例,默认使用0号数据库
public static IDatabase GetDatabase()
{
return Connection.GetDatabase();
}
}
基础缓存读写操作
写入缓存
写入缓存支持设置过期时间,避免缓存数据一直占用内存。以下是写入字符串类型缓存的示例:
using StackExchange.Redis;
using System;
public class CacheService
{
// 写入缓存,设置过期时间
public static bool SetCache(string key, string value, TimeSpan? expireTime = null)
{
IDatabase db = RedisHelper.GetDatabase();
// 如果传入了过期时间就设置,否则不设置过期时间
if (expireTime.HasValue)
{
return db.StringSet(key, value, expireTime);
}
else
{
return db.StringSet(key, value);
}
}
}
读取缓存
读取缓存时先判断key是否存在,存在则返回对应的值,不存在返回空。示例代码如下:
using StackExchange.Redis;
using System;
public class CacheService
{
// 读取缓存
public static string GetCache(string key)
{
IDatabase db = RedisHelper.GetDatabase();
// 判断key是否存在
if (db.KeyExists(key))
{
return db.StringGet(key);
}
return null;
}
}
删除缓存操作
当缓存数据失效或者需要更新时,可以主动删除对应的缓存。删除缓存的示例代码如下:
using StackExchange.Redis;
using System;
public class CacheService
{
// 删除指定key的缓存
public static bool DeleteCache(string key)
{
IDatabase db = RedisHelper.GetDatabase();
return db.KeyDelete(key);
}
}
实际使用示例
以下是一个完整的调用示例,演示如何写入、读取、删除缓存:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
string cacheKey = "user_1001";
string cacheValue = "张三,25岁,工程师";
// 写入缓存,设置过期时间为10分钟
bool setResult = CacheService.SetCache(cacheKey, cacheValue, TimeSpan.FromMinutes(10));
Console.WriteLine($"写入缓存结果:{setResult}");
// 读取缓存
string getValue = CacheService.GetCache(cacheKey);
Console.WriteLine($"读取到的缓存值:{getValue}");
// 删除缓存
bool deleteResult = CacheService.DeleteCache(cacheKey);
Console.WriteLine($"删除缓存结果:{deleteResult}");
// 再次读取缓存,此时应该返回空
string getValueAfterDelete = CacheService.GetCache(cacheKey);
Console.WriteLine($"删除后读取缓存值:{getValueAfterDelete ?? "空"}");
}
}
注意事项
- Redis连接字符串中的密码如果为空,可以直接去掉password=部分,或者保留空值
- 生产环境建议给Redis设置密码,避免未授权访问
- 缓存的key命名建议加上业务前缀,比如user_、order_,避免不同业务的key冲突
- 如果缓存的是对象,需要先将对象序列化为字符串再存储,读取时再反序列化
RedisStackExchange_Redis.NETCache修改时间:2026-06-26 10:03:22