Redis哈希HMSET是否在事务中执行?并发HGETALL场景疑问
Great questions! Let's break them down one by one to clear things up:
1. Can the HMSET command for Redis Hashes be executed within a transaction?
Absolutely. Redis transactions work by queuing commands with MULTI and executing them atomically as a group with EXEC — and HMSET fits right into this workflow.
A quick side note: Starting in Redis 4.0, HMSET is technically deprecated in favor of HSET (since HSET now supports setting multiple key-value pairs in a single call). But don't worry — both HMSET and the updated multi-field HSET can be used in transactions without any issues.
Here's a quick example of how that looks in practice:
MULTI HMSET myhash field1 "foo" field2 "bar" HGET myhash field1 EXEC
When you run EXEC, all queued commands (including the HMSET) will execute as a single atomic unit. No other client can modify myhash in between the queued commands, which is the core benefit of Redis transactions.
2. When executing HMSET myhash field1 "Hello" field2 "World", can another client using HGETALL only retrieve the field1 data?
Nope, that's impossible — and it all comes down to Redis's core design principle: every single command is atomic.
What this means for your HMSET call is that the entire operation (setting both field1 and field2 at the same time) either completes fully, or doesn't run at all from the perspective of other clients. So another client calling HGETALL will only see one of two states:
- The state of
myhashbefore theHMSETstarted (this could be empty ifmyhashdidn't exist, or whatever key-value pairs were stored there previously) - The state after the
HMSETfinished (with bothfield1andfield2present and populated)
There's no middle ground where only field1 is visible. Redis never partially executes single commands, so you'll never get a half-updated hash from another client's read.
内容的提问来源于stack exchange,提问作者Azarea

