Nuget 套件 :StackExchange.Redis
/*使用Key-Value*/
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("DBIP,allowAdmin=true"))
{
//取Server
var server = conn.GetServer(conn.GetEndPoints().First());
//取操作介面
IDatabase cache = conn.GetDatabase();
//確保Key全空
server.FlushDatabase();
//key的value +1 , 如果沒有key, 自動新增
cache.StringIncrement("abc", 1);
//取得 Redis Key 所有資料
foreach (var key in server.Keys())
{
string key = key.ToString() ;
int value = Convert.ToInt32(cache.StringGet(key.ToString())) ;
}
}
/*使用Key-Hash-Value*/
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("192.168.18.46"))
{
IDatabase cache = conn.GetDatabase();
const string DictKey = "KeyName";
//確保(單一)Key全空
cache.KeyDeleteAsync(DictKey);
//key-hash的value +1 , 如果沒有hash, 自動新增
cache.HashIncrementAsync(DictKey, "abc", 1);
//取得 Redis Key 所有資料
HashEntry[] RedisQuery = cache.HashGetAll(DictKey);
foreach (HashEntry rq in RedisQuery)
{
string key = rq.Name ;
int value = Convert.ToInt32(rq.Value) ;
}
//取完Redis,清空(單一)Key
cache.KeyDeleteAsync(DictKey);
}
/*使用Key-Value*/
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("DBIP,allowAdmin=true"))
{
//取Server
var server = conn.GetServer(conn.GetEndPoints().First());
//取操作介面
IDatabase cache = conn.GetDatabase();
//確保Key全空
server.FlushDatabase();
//key的value +1 , 如果沒有key, 自動新增
cache.StringIncrement("abc", 1);
//取得 Redis Key 所有資料
foreach (var key in server.Keys())
{
string key = key.ToString() ;
int value = Convert.ToInt32(cache.StringGet(key.ToString())) ;
}
}
/*使用Key-Hash-Value*/
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("192.168.18.46"))
{
IDatabase cache = conn.GetDatabase();
const string DictKey = "KeyName";
//確保(單一)Key全空
cache.KeyDeleteAsync(DictKey);
//key-hash的value +1 , 如果沒有hash, 自動新增
cache.HashIncrementAsync(DictKey, "abc", 1);
//取得 Redis Key 所有資料
HashEntry[] RedisQuery = cache.HashGetAll(DictKey);
foreach (HashEntry rq in RedisQuery)
{
string key = rq.Name ;
int value = Convert.ToInt32(rq.Value) ;
}
//取完Redis,清空(單一)Key
cache.KeyDeleteAsync(DictKey);
}
留言
張貼留言