Hello i have the following problem:
I have a hash that contains strings.This hash will get queried by multiple users.
When a user comes with a Key
to first check if it exists in this hash and if it does not, add it.
How can I make the operations "check if hash exists", "add if not exists" atomic?
Reading the redis documentation it seems Watch
is what I need. Basically start a transaction and end it if the variable changes.
I have tried using Condition.HashNotExists
to no avail:
class Program {
public static async Task<bool> LockFileForEditAsync(int fileId) {
var database = ConnectionMultiplexer.Connect(CON).GetDatabase();
var exists = await database.HashExistsAsync("files", fileId); //this line is for shorting the transaction if hash exists
if (exists) {
return false;
}
var tran = database.CreateTransaction();
tran.AddCondition(Condition.HashNotExists("files", fileId));
var setKey = tran.HashSetAsync("files", new HashEntry[] { new HashEntry(fileId, 1) });
var existsTsc = tran.HashExistsAsync("files", fileId);
if (!await tran.ExecuteAsync()) {
return false;
}
var rezult = await existsTsc;
return rezult;
}
public const string CON = "127.0.0.1:6379,ssl=False,allowAdmin=True,abortConnect=False,defaultDatabase=0";
static async Task Main(string[] args) {
int fid = 1;
var locked = await LockFileForEditAsync(fid);
}
}
If I connect via redis-cli
and issue in the cli
: hset files {fileId} 1
, right BEFORE I issue the ExecuteAsync
(in the debugger) I am expecting this transaction to fail since I placed the Condition
. However it does not happen so.
How can I basically use redis commands place something like a lock on the two operations:
- Check if hashentry exists
- Add hashentry