私はいくつかのAPI呼び出しに送るカウンタを生成する必要があります。私のアプリケーションは複数のノードで動作しているので、独自のカウンタを生成したいと思っていました。 私はコードRedisはロック付きでインクリメントされています
public static long GetTransactionCountForUser(int telcoId)
{
long valreturn = 0;
string key = "TelcoId:" + telcoId + ":Sequence";
if (Muxer != null && Muxer.IsConnected && (Muxer.GetDatabase()) != null)
{
IDatabase db = Muxer.GetDatabase();
var val = db.StringGet(key);
int maxVal = 999;
if (Convert.ToInt32(val) < maxVal)
{
valreturn = db.StringIncrement(key);
}
else
{
bool isdone = db.StringSet(key, valreturn);
//db.SetAdd(key,new RedisValue) .StringIncrement(key, Convert.ToDouble(val))
}
}
return valreturn;
}
して実行するタスク並列librayを経由してそれをテストして、次の試してみました。 私の最後のロジックは
public static long GetSequenceNumberForTelcoApiCallViaLuaScript(int telcoId)
{
long valreturn = 0;
int maxIncrement = 9999;//todo via configuration
if (true)//todo via configuration
{
IDatabase db;
string key = "TelcoId:" + telcoId + ":SequenceNumber";
if (Muxer != null && Muxer.IsConnected && (db = Muxer.GetDatabase()) != null)
{
valreturn = (int)db.ScriptEvaluate(@"
local result = redis.call('incr', KEYS[1])
if result > tonumber(ARGV[1]) then
result = 1
redis.call('set', KEYS[1], result)
end
return result", new RedisKey[] { key }, flags: CommandFlags.HighPriority, values: new RedisValue[] { maxIncrement });
}
}
return valreturn;
}
を通知を受けるだろう、挿入を行うと、返されたSCOPE_IDENTITY()を使用します。常にユニークなものを返すべきです。 –
dbの挿入/ dbの往復を避けたかったのです。私はCache Via Redisをサポートしています。これは完全に –
に調整したかったのです。@ KamranShahid 'string.Format'を使用してパラメータ化してください。私は好ましい方法を示すために私の例を編集します –