set.3valkey - Man Page

Sets the string value of a key, ignoring its type. The key is created if it doesn’t exist.

Synopsis

SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]

Description

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

Options

The SET command supports a set of options that modify its behavior:

Note: Since the SET command options can replace SETNX, SETEX, PSETEX, GETSET, it is possible that in future versions of Valkey these commands will be deprecated and finally removed.

Reply

Resp2

Any of the following:

Resp3

Any of the following:

Complexity

O(1)

Acl Categories

@slow @string @write

History

Examples

127.0.0.1:6379> SET mykey "Hello"
OK
127.0.0.1:6379> GET mykey
"Hello"
127.0.0.1:6379> 
127.0.0.1:6379> SET anotherkey "will expire in a minute" EX 60
OK

Patterns

Note: The following pattern is discouraged in favor of valkey-distlock(7) the Redlock algorithm which is only a bit more complex to implement, but offers better guarantees and is fault tolerant.

The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Valkey.

A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.

The lock will be auto-released after the expire time is reached.

It is possible to make this system more robust modifying the unlock schema as follows:

  • Instead of setting a fixed string, set a non-guessable large random string, called token.
  • Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.

This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.

An example of unlock script would be similar to the following:

if server.call("get",KEYS[1]) == ARGV[1]
then
    return server.call("del",KEYS[1])
else
    return 0
end

The script should be called with EVAL ...script... 1 resource-name token-value

See Also

append(3valkey), decr(3valkey), decrby(3valkey), get(3valkey), getdel(3valkey), getex(3valkey), getrange(3valkey), incr(3valkey), incrby(3valkey), incrbyfloat(3valkey), lcs(3valkey), mget(3valkey), mset(3valkey), msetnx(3valkey), setrange(3valkey), strlen(3valkey)

Info

2024-09-23 8.0.0 Valkey Command Manual