我正在将 StackExchange.Redis 客户端与 Azure Redis 缓存服务结合使用。这是我的类(class),
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缓存中删除所有项目或单个项目。
请您参考如下方法:
要删除单个项目:
_cache.KeyDelete(key);
要删除全部涉及FLUSHDB
或FLUSHALL
redis命令;两者都可以在 StackExchange.Redis 中使用;但是,for reasons discussed here ,它们不在 IDatabase
API 上(因为:它们影响服务器,而不是逻辑数据库)。
根据“那么我该如何使用它们?”在该页面上:
server.FlushDatabase(); // to wipe a single database, 0 by default
server.FlushAllDatabases(); // to wipe all databases
(很可能在多路复用器上使用 GetEndpoints()
之后)