Redisオペレーションヘルプクラス
以前、Redisについて紹介した文章がありました.自分の実践操作の中で、自分でRedis操作に関するクラスライブラリを書きました.
まずNugetからStackExchangeを追加する.Redisパッケージ
1.Redis接続オブジェクト管理ヘルプクラス
データベース接続はconfigプロファイルから読み込まれ、構成例
2、Redis操作ヘルプクラス
3.Redis操作オブジェクトを格納する共通クラス
4、使用例
GlobalでWebプロジェクトを新規作成します.asax.csファイルのApplication_Start()メソッドでは、次のコードを追加します.
Redisからのクエリー・データの例
Redisへのデータの新規作成例
まずNugetからStackExchangeを追加する.Redisパッケージ
1.Redis接続オブジェクト管理ヘルプクラス
using Mvc.Base;
using Mvc.Base.Log;
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RedisApi
{
///
/// Redis
///
public static class RedisConnectionHelp
{
///
/// Redis
///
private static readonly string RedisConnectionString = BaseMethod.GetAppValue("RedisConnectionString");
///
///
///
private static readonly object Locker = new object();
///
/// Redis
///
private static ConnectionMultiplexer _instance;
///
///
///
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
///
/// Redis
///
///
private static ConnectionMultiplexer GetManager()
{
ConnectionMultiplexer connect = null;
try
{
connect = ConnectionMultiplexer.Connect(RedisConnectionString);
}
catch
{
return null;
}
//
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region
///
///
///
///
///
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
LogHelper.WriteLog("Configuration changed: " + e.EndPoint);
}
///
///
///
///
///
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
LogHelper.WriteLog("ErrorMessage: " + e.Message);
}
///
///
///
///
///
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
LogHelper.WriteLog("ConnectionRestored: " + e.EndPoint);
}
///
/// ,
///
///
///
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
LogHelper.WriteLog(" :Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
///
///
///
///
///
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
LogHelper.WriteLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
///
/// redis
///
///
///
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
LogHelper.WriteLog("InternalError:Message" + e.Exception.Message);
}
#endregion
}
}
データベース接続はconfigプロファイルから読み込まれ、構成例
2、Redis操作ヘルプクラス
using Mvc.Base.Data;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisApi
{
///
/// Redis
///
public class RedisHelper
{
///
///
///
private int DbNum;
///
///
///
private readonly ConnectionMultiplexer RedisConn;
///
/// Redis
///
///
public RedisHelper(int _DbNum)
{
DbNum = _DbNum;
RedisConn = RedisConnectionHelp.Instance;
}
#region ----------------------String ----------------------
///
/// String
///
///
///
///
public bool StringSet(string Key, string Value)
{
try
{
return Do(db => db.StringSet(Key, Value));
}
catch
{
return false;
}
}
///
/// String
///
/// String
///
public bool StringSet(Dictionary Values)
{
try
{
List> _KeyValuePair = new List>();
foreach (var item in Values.Keys)
{
_KeyValuePair.Add(new KeyValuePair(item, Values[item]));
}
return Do(db => db.StringSet(_KeyValuePair.ToArray()));
}
catch
{
return false;
}
}
///
/// String
///
/// Redis Key
///
public string StringGet(string Key)
{
try
{
return Do(db => db.StringGet(Key));
}
catch
{
return null;
}
}
///
/// String
///
/// Value
///
public List StringGet(List ListKey)
{
try
{
return RedisValueToList(Do(db => db.StringGet(ListToRedisKey(ListKey))));
}
catch
{
return null;
}
}
///
///
///
///
/// ( )
///
public double StringIncrement(string Key, double Value)
{
try
{
return Do(db => db.StringIncrement(Key, Value));
}
catch
{
return -1;
}
}
///
///
///
///
/// ( )
///
public double StringDecrement(string Key, double Value)
{
try
{
return Do(db => db.StringDecrement(Key, Value));
}
catch
{
return -1;
}
}
///
///
///
///
///
///
///
public string StringGetRange(string Key, long Start, long End)
{
try
{
return Do(db => db.StringGetRange(Key, Start, End));
}
catch
{
return null;
}
}
///
/// ,
///
///
///
///
public long StringAppend(string Key, string Value)
{
try
{
return Do(db => db.StringAppend(Key, Value));
}
catch
{
return -1;
}
}
#endregion
#region ---------------------- Hash ----------------------
///
/// Hash
///
///
/// Hash
/// Hash
///
public bool HashSet(string Key, string HashKey, string HashValue)
{
try
{
return Do(db =>
{
return db.HashSet(Key, HashKey, HashValue);
});
}
catch
{
return false;
}
}
///
/// Hash
///
///
/// Hash
///
public void HashSet(string Key, Dictionary HashData)
{
try
{
List HashTable = new List();
foreach (string item in HashData.Keys)
{
HashTable.Add(new HashEntry(item, HashData[item]));
}
var db = RedisConn.GetDatabase(DbNum);
db.HashSet(Key, HashTable.ToArray());
}
catch
{
}
}
///
/// Hash
///
///
///
public long HashLength(string Key)
{
try
{
return Do(db => db.HashLength(Key));
}
catch
{
return -1;
}
}
///
/// Hash
///
///
/// HashKey
/// ,
///
public double HashIncrement(string Key, string HashKey, double Value)
{
try
{
return Do(db => db.HashIncrement(Key, HashKey, Value));
}
catch
{
return -1;
}
}
///
/// Hash
///
///
/// HashKey
/// ,
///
public double HashDecrement(string Key, string HashKey, double Value)
{
try
{
return Do(db => db.HashDecrement(Key, HashKey, Value));
}
catch
{
return -1;
}
}
///
/// Hash , 0
///
///
///
public Dictionary HashGetAll(string Key)
{
try
{
HashEntry[] HashTable = Do(db => db.HashGetAll(Key));
Dictionary Result = new Dictionary();
for (int i = 0; i < HashTable.Length; i++)
{
Result.Add(HashTable[i].Name, HashTable[i].Value.ToString());
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
/// Hash Key
///
///
/// Hash
///
public string HashGet(string Key, string HashKey)
{
try
{
return Do(db => db.HashGet(Key, HashKey));
}
catch
{
return null;
}
}
///
/// Hash Key
///
///
/// Hash
///
public List HashGet(string Key, string[] HashKeys)
{
try
{
RedisValue[] _RedisValue = new RedisValue[HashKeys.Length];
for (int i = 0; i < HashKeys.Length; i++)
{
_RedisValue[i] = HashKeys[i];
}
return Do(db =>
{
RedisValue[] Value = db.HashGet(Key, _RedisValue);
List Result = new List();
for (int i = 0; i < Value.Length; i++)
{
Result.Add(Value[i].ToString());
}
return Result;
});
}
catch
{
return new List();
}
}
///
/// Hash Key
///
///
/// Hash
///
public bool HashExists(string Key, string HashKey)
{
try
{
return Do(db => db.HashExists(Key, HashKey));
}
catch
{
return false;
}
}
///
/// Hash
///
///
/// Hash
///
public bool HashDelete(string Key, string HashKey)
{
try
{
return Do(db => db.HashDelete(Key, HashKey));
}
catch
{
return false;
}
}
///
/// Hash
///
///
/// Hash
///
public long HashDelete(string Key, string[] HashKeys)
{
try
{
RedisValue[] _RedisValue = new RedisValue[HashKeys.Length];
for (int i = 0; i < HashKeys.Length; i++)
{
_RedisValue[i] = HashKeys[i];
}
return Do(db => db.HashDelete(Key, _RedisValue));
}
catch
{
return -1;
}
}
///
/// Hash Key
///
///
///
public List HashKeys(string Key)
{
try
{
return Do(db => RedisValueToList(db.HashKeys(Key)));
}
catch
{
return new List();
}
}
#endregion
#region ------------------------List ----------------------
///
/// , List
///
///
///
public long ListRightPush(string Key, string Value)
{
try
{
return Do(db => db.ListRightPush(Key, Value));
}
catch
{
return -1;
}
}
///
/// ,
///
///
///
public string ListRightPop(string Key)
{
try
{
return Do(db => db.ListRightPop(Key));
}
catch
{
return null;
}
}
///
/// , List
///
///
///
public long ListLeftPush(string Key, string Value)
{
try
{
return Do(db => db.ListLeftPush(Key, Value));
}
catch
{
return -1;
}
}
///
/// ,
///
///
///
public string ListLeftPop(string Key)
{
try
{
return Do(db => db.ListLeftPop(Key));
}
catch
{
return null;
}
}
///
/// List
///
///
///
public long ListRemove(string Key, string Value)
{
try
{
return Do(db => db.ListRemove(Key, Value));
}
catch
{
return -1;
}
}
///
/// Key List
///
///
///
///
///
public List ListGet(string Key, long Start = 1, long End = 0)
{
try
{
Start--;
End--;
return RedisValueToList(Do(db => db.ListRange(Key, Start, End)));
}
catch
{
return new List();
}
}
///
/// 。
///
///
/// , 。-1 ,-2
///
public string ListGetByIndex(string Key, long Index)
{
try
{
return Do(db => db.ListGetByIndex(Key, Index));
}
catch
{
return null;
}
}
///
///
///
///
///
public long ListLength(string Key)
{
try
{
return Do(redis => redis.ListLength(Key));
}
catch
{
return -1;
}
}
#endregion
#region ------------------------Set -----------------------
///
/// Set
///
///
///
///
public bool SetAdd(string Key, string Value)
{
try
{
return Do(db => db.SetAdd(Key, Value));
}
catch
{
return false;
}
}
///
/// Set
///
///
///
///
public long SetAdd(string Key, List Value)
{
try
{
return Do(db => db.SetAdd(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
///
/// Set ,
///
/// ,0: ,1: ,2:
///
///
public List SetCombine(int Operation, List Keys)
{
try
{
SetOperation operation = SetOperation.Union;
switch (Operation)
{
case 1:
operation = SetOperation.Intersect;
break;
case 2:
operation = SetOperation.Difference;
break;
}
return RedisValueToList(Do(db => db.SetCombine(operation, ListToRedisKey(Keys))));
}
catch
{
return new List();
}
}
///
/// 2 Set ,
///
/// ,0: ,1: ,2:
/// 1
/// 2
///
public List SetCombine(int Operation, string First, string Second)
{
try
{
SetOperation operation = SetOperation.Union;
switch (Operation)
{
case 1:
operation = SetOperation.Intersect;
break;
case 2:
operation = SetOperation.Difference;
break;
}
return RedisValueToList(Do(db => db.SetCombine(operation, First, Second)));
}
catch
{
return new List();
}
}
///
/// Set
///
///
///
public long SetLength(string Key)
{
try
{
return Do(db => db.SetLength(Key));
}
catch
{
return -1;
}
}
///
/// Set
///
///
///
public List SetMembers(string Key)
{
try
{
return RedisValueToList(Do(db => db.SetMembers(Key)));
}
catch
{
return new List();
}
}
///
/// Set
///
///
///
///
public bool SetRemove(string Key, string Value)
{
try
{
return Do(db => db.SetRemove(Key, Value));
}
catch
{
return false;
}
}
///
/// Set
///
///
///
///
public long SetRemove(string Key, List Value)
{
try
{
return Do(db => db.SetRemove(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
#endregion
#region --------------------SortedSet --------------------
///
/// SortedSet
///
///
///
/// ,
///
public bool SortedSetAdd(string Key, string Value, double OrderValue)
{
try
{
return Do(db => db.SortedSetAdd(Key, Value, OrderValue));
}
catch
{
return false;
}
}
///
/// SortedSet
///
///
/// { , }
///
public long SortedSetAdd(string Key, Dictionary SortedSetData)
{
try
{
List SortedSetTable = new List();
foreach (var item in SortedSetData.Keys)
{
SortedSetTable.Add(new SortedSetEntry(item, SortedSetData[item]));
}
return Do(db => db.SortedSetAdd(Key, SortedSetTable.ToArray()));
}
catch
{
return -1;
}
}
///
/// SortedSet
///
///
///
public long SortedSetLength(string Key)
{
try
{
return Do(db => db.SortedSetLength(Key));
}
catch
{
return -1;
}
}
///
/// SortedSet
///
///
///
/// ,
///
public double SortedSetIncrement(string Key, string SortedSetValue, double Value)
{
try
{
return Do(db => db.SortedSetIncrement(Key, SortedSetValue, Value));
}
catch
{
return -1;
}
}
///
/// SortedSet
///
///
///
/// ,
///
public double SortedSetDecrement(string Key, string SortedSetValue, double Value)
{
try
{
return Do(db => db.SortedSetDecrement(Key, SortedSetValue, Value));
}
catch
{
return -1;
}
}
///
///
///
///
///
///
/// 0: - 1: -
///
public List SortedSetRangeByRank(string Key, long Start = 1, long End = 0, int OrderType = 0)
{
try
{
Order _Order = default(Order);
SortedSetParm(ref Start, ref End, OrderType, ref _Order);
return RedisValueToList(Do(db => db.SortedSetRangeByRank(Key, Start, End, _Order)));
}
catch
{
return new List();
}
}
///
///
///
///
///
///
/// 0: - 1: -
///
public Dictionary SortedSetRangeByRankWithScores(string Key, long Start = 1, long End = 0, int OrderType = 0)
{
try
{
Order _Order = default(Order);
SortedSetParm(ref Start, ref End, OrderType, ref _Order);
SortedSetEntry[] _SortedSetEntry = Do(db => db.SortedSetRangeByRankWithScores(Key, Start, End, _Order));
Dictionary Result = new Dictionary();
foreach (var item in _SortedSetEntry)
{
Result.Add(item.Element, item.Score);
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
///
///
///
///
///
/// 0: - 1: -
///
public List SortedSetRangeByScore(string Key, long Start = 1, long End = 0, int OrderType = 0)
{
try
{
Order _Order = default(Order);
SortedSetParm(ref Start, ref End, OrderType, ref _Order);
return RedisValueToList(Do(db => db.SortedSetRangeByScore(Key, Start, End, Exclude.None, _Order)));
}
catch
{
return new List();
}
}
///
///
///
///
///
///
/// 0: - 1: -
///
public Dictionary SortedSetRangeByScoreWithScores(string Key, long Start = 1, long End = 0, int OrderType = 0)
{
try
{
Order _Order = default(Order);
SortedSetParm(ref Start, ref End, OrderType, ref _Order);
SortedSetEntry[] _SortedSetEntry = Do(db => db.SortedSetRangeByScoreWithScores(Key, Start, End, Exclude.None, _Order));
Dictionary Result = new Dictionary();
foreach (var item in _SortedSetEntry)
{
Result.Add(item.Element, item.Score);
}
return Result;
}
catch
{
return new Dictionary();
}
}
///
///
///
///
///
///
public long? SortedSetRank(string Key, string Value)
{
try
{
return Do(db => db.SortedSetRank(Key, Value)) + 1;
}
catch
{
return -1;
}
}
///
///
///
///
///
///
public double? SortedSetScore(string Key, string Value)
{
try
{
return Do(db => db.SortedSetScore(Key, Value));
}
catch
{
return -1;
}
}
///
/// SortedSet
///
///
///
///
public bool SortedSetRemove(string Key, string Value)
{
try
{
return Do(db => db.SortedSetRemove(Key, Value));
}
catch
{
return false;
}
}
///
/// SortedSet
///
///
///
///
public long SortedSetRemove(string Key, List Value)
{
try
{
return Do(db => db.SortedSetRemove(Key, ListToRedisValue(Value)));
}
catch
{
return -1;
}
}
///
///
///
///
///
///
///
public long SortedSetRemoveRangeByRank(string Key, long Start, long End)
{
try
{
Start--;
End--;
return Do(db => db.SortedSetRemoveRangeByRank(Key, Start, End));
}
catch
{
return -1;
}
}
///
///
///
///
///
///
///
public long SortedSetRemoveRangeByScore(string Key, double Start, double End)
{
try
{
return Do(db => db.SortedSetRemoveRangeByScore(Key, Start, End));
}
catch
{
return -1;
}
}
#endregion
#region ------------------------Key -----------------------
///
///
///
///
///
public bool KeyDelete(string Key)
{
try
{
return Do(db => db.KeyDelete(Key));
}
catch
{
return false;
}
}
///
///
///
///
///
public long KeyDelete(List Keys)
{
try
{
return Do(db => db.KeyDelete(ListToRedisKey(Keys)));
}
catch
{
return -1;
}
}
///
///
///
///
///
public bool KeyExists(string Key)
{
try
{
return Do(db => db.KeyExists(Key));
}
catch
{
return false;
}
}
///
/// Key
///
///
///
///
public bool KeyRename(string Key, string NewKey)
{
try
{
return Do(db => db.KeyRename(Key, NewKey));
}
catch
{
return false;
}
}
///
///
///
///
/// ( + ): S: M: H: D: :100S (100 )
///
public bool KeyExpire(string Key, string Expiry)
{
try
{
string Type = Expiry.Substring(Expiry.Length - 1, 1).ToUpper();
string Value = Expiry.Substring(0, Expiry.Length - 1);
TimeSpan? Ts = default(TimeSpan?);
switch (Type)
{
case "S":
Ts = TimeSpan.FromSeconds(Convert.ToDouble(Value));
break;
case "M":
Ts = TimeSpan.FromMinutes(Convert.ToDouble(Value));
break;
case "H":
Ts = TimeSpan.FromHours(Convert.ToDouble(Value));
break;
case "D":
Ts = TimeSpan.FromDays(Convert.ToDouble(Value));
break;
}
return Do(db => db.KeyExpire(Key, Ts));
}
catch
{
return false;
}
}
#endregion
#region ------------------------ ------------------------
///
///
///
///
///
///
///
private void SortedSetParm(ref long Start, ref long End, int OrderType, ref Order _Order)
{
Start--;
End--;
_Order = OrderType == 0 ? Order.Ascending : Order.Descending;
}
///
/// List RedisValue
///
/// List
///
private RedisValue[] ListToRedisValue(List List)
{
List _RedisValue = new List();
try
{
for (int i = 0; i < List.Count; i++)
{
_RedisValue.Add(List[i]);
}
return _RedisValue.ToArray();
}
catch
{
return new List().ToArray();
}
}
///
/// RedisValue List
///
/// RedisValue
///
private List RedisValueToList(RedisValue[] _RedisValue)
{
List List = new List();
try
{
for (int i = 0; i < _RedisValue.Length; i++)
{
List.Add(_RedisValue[i]);
}
return List;
}
catch
{
return new List();
}
}
///
/// List RedisKey
///
/// List
///
private RedisKey[] ListToRedisKey(List List)
{
List RedisKey = new List();
try
{
for (int i = 0; i < List.Count; i++)
{
RedisKey.Add(List[i]);
}
return RedisKey.ToArray();
}
catch
{
return new List().ToArray();
}
}
///
/// RedisKey List
///
/// RedisKey
///
private List RedisKeyToList(RedisKey[] _RedisKey)
{
List List = new List();
try
{
for (int i = 0; i < _RedisKey.Length; i++)
{
List.Add(_RedisKey[i]);
}
return List;
}
catch
{
return new List();
}
}
///
/// Redis
///
private T Do(Func func)
{
var database = RedisConn.GetDatabase(DbNum);
return func(database);
}
#endregion
#region
///
/// Redis
///
///
public bool GetConnectSate()
{
bool RedisIsConnected = false;
try
{
if (RedisCmd.Api != null)
{
RedisIsConnected = RedisCmd.Api.RedisConn.IsConnected ? true : false;
return RedisIsConnected;
}
return false;
}
catch
{
return false;
}
}
///
///
///
///
public IDatabase GetDatabase()
{
return RedisConn.GetDatabase(DbNum);
}
public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
}
public IServer GetServer(string hostAndPort)
{
return RedisConn.GetServer(hostAndPort);
}
#endregion
#region
///
/// Redis
///
///
///
//public void Subscribe(string subChannel, Action handler = null)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// sub.Subscribe(subChannel, (channel, message) =>
// {
// if (handler == null)
// {
// Console.WriteLine(subChannel + " :" + message);
// }
// else
// {
// handler(channel, message);
// }
// });
//}
///
/// Redis
///
///
///
///
///
//public long Publish(string channel, T msg)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// return sub.Publish(channel, (msg));
//}
///
/// Redis
///
///
//public void Unsubscribe(string channel)
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// sub.Unsubscribe(channel);
//}
///
/// Redis
///
//public void UnsubscribeAll()
//{
// ISubscriber sub = RedisConn.GetSubscriber();
// sub.UnsubscribeAll();
//}
#endregion
}
}
3.Redis操作オブジェクトを格納する共通クラス
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisApi
{
///
/// Redis
///
public static class RedisCmd
{
///
/// Redis
///
public static RedisHelper Api = null;
}
}
4、使用例
GlobalでWebプロジェクトを新規作成します.asax.csファイルのApplication_Start()メソッドでは、次のコードを追加します.
if (RedisCmd.Api == null)
{
RedisHelper RedisApi = new RedisHelper(0);
RedisCmd.Api = RedisApi;
}
Redisからのクエリー・データの例
if (RedisCmd.Api.KeyExists("Home_Notify"))
{
ViewBag.Notify = RedisCmd.Api.HashGet("Home_Notify", "Title");
ViewBag.ID = RedisCmd.Api.HashGet("Home_Notify", "AutoID");
}
Redisへのデータの新規作成例
RedisCmd.Api.HashSet("Home_Notify", "Title", NotifyText[0].Title);
RedisCmd.Api.HashSet("Home_Notify", "AutoID", NotifyText[0].AutoID.ToString());
RedisCmd.Api.KeyExpire("Home_Notify", "2h");