我正在使用带有 Azure Redis 缓存服务的 StackExchange.Redis 客户端。这是我的课,
public class RedisCacheService : ICacheService
{
private readonly ISettings _settings;
private readonly IDatabase _cache;
public RedisCacheService(ISettings settings)
{
_settings = settings;
var connectionMultiplexer = ConnectionMultiplexer.Connect(settings.RedisConnection);
_cache = connectionMultiplexer.GetDatabase();
}
public bool Exists(string key)
{
return _cache.KeyExists(key);
}
public void Save(string key, string value)
{
var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
_cache.StringSet(key, value, ts);
}
public string Get(string key)
{
return _cache.StringGet(key);
}
public void Remove(string key)
{
// How to remove one
}
public void Clear()
{
// How to remove all
}
}
更新:在 Marc 的帮助下,这是我的最后一堂课
public class RedisCacheService : ICacheService
{
private readonly ISettings _settings;
private readonly IDatabase _cache;
private static ConnectionMultiplexer _connectionMultiplexer;
static RedisCacheService()
{
var connection = ConfigurationManager.AppSettings["RedisConnection"];
_connectionMultiplexer = ConnectionMultiplexer.Connect(connection);
}
public RedisCacheService(ISettings settings)
{
_settings = settings;
_cache = _connectionMultiplexer.GetDatabase();
}
public bool Exists(string key)
{
return _cache.KeyExists(key);
}
public void Save(string key, string value)
{
var ts = TimeSpan.FromMinutes(_settings.CacheTimeout);
_cache.StringSet(key, value, ts);
}
public string Get(string key)
{
return _cache.StringGet(key);
}
public void Remove(string key)
{
_cache.KeyDelete(key);
}
public void Clear()
{
var endpoints = _connectionMultiplexer.GetEndPoints(true);
foreach (var endpoint in endpoints)
{
var server = _connectionMultiplexer.GetServer(endpoint);
server.FlushAllDatabases();
}
}
}
现在我不知道如何从 redis 缓存中删除所有项目或单个项目。