[フレーム]
Docs Pricing
Login Book a meeting Try Redis

SET

SET key value [NX | XX | IFEQ ifeq-value | IFNE ifne-value |
 IFDEQ ifdeq-digest | IFDNE ifdne-digest] [GET] [EX seconds |
 PX milliseconds | EXAT unix-time-seconds |
 PXAT unix-time-milliseconds | KEEPTTL]
Available since:
Redis Open Source 1.0.0
Time complexity:
O(1)
ACL categories:
@write, @string, @slow,
Compatibility:
Redis Enterprise and Redis Cloud compatibility

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 Redis these commands will be deprecated and finally removed.

Hash Digest

A hash digest is a fixed-size numerical representation of a string value, computed using the XXH3 hash algorithm. Redis uses this hash digest for efficient comparison operations without needing to compare the full string content. You can retrieve a key's hash digest using the DIGEST command, which returns it as a hexadecimal string that you can use with the IFDEQ and IFDNE options, and also the DELEX command's IFDEQ and IFDNE options.

Examples

SET mykey "Hello" GET mykey

SET anotherkey "will expire in a minute" EX 60

Code examples

"""
Code samples for data structure store quickstart pages:
 https://redis.io/docs/latest/develop/get-started/data-store/
"""
import redis
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
res = r.set("bike:1", "Process 134")
print(res)
# >>> True
res = r.get("bike:1")
print(res)
# >>> "Process 134"
Python Quick-Start
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect().catch(console.error);
await client.set('bike:1', 'Process 134');
const value = await client.get('bike:1');
console.log(value);
// returns 'Process 134'

await client.close();
Node.js Quick-Start
packageio.redis.examples;importredis.clients.jedis.RedisClient;publicclass SetGetExample{publicvoidrun(){RedisClientjedis=RedisClient.create("redis://localhost:6379");Stringstatus=jedis.set("bike:1","Process 134");if("OK".equals(status))System.out.println("Successfully added a bike.");Stringvalue=jedis.get("bike:1");if(value!=null)System.out.println("The name of the bike is: "+value+".");jedis.close();}}
Java-Sync Quick-Start
package example_commands_test
import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
)
func ExampleClient_Set_and_get() {
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
		Password: "", // no password docs
		DB: 0, // use default DB
	})
	err := rdb.Set(ctx, "bike:1", "Process 134", 0).Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("OK")
	value, err := rdb.Get(ctx, "bike:1").Result()
	if err != nil {
		panic(err)
	}
	fmt.Printf("The name of the bike is %s", value)
}
Go Quick-Start
using NRedisStack.Tests;
using StackExchange.Redis;
public class SetGetExample
{
 public void Run()
 {
 var muxer = ConnectionMultiplexer.Connect("localhost:6379");
 var db = muxer.GetDatabase();
 bool status = db.StringSet("bike:1", "Process 134");
 if (status)
 Console.WriteLine("Successfully added a bike.");
 var value = db.StringGet("bike:1");
 if (value.HasValue)
 Console.WriteLine("The name of the bike is: " + value + ".");
 }
}
C#-Sync Quick-Start

Patterns

Note: The following pattern is discouraged in favor of 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 Redis.

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:

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 redis.call("get",KEYS[1]) == ARGV[1]
then
 return redis.call("del",KEYS[1])
else
 return 0
end

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

Redis Enterprise and Redis Cloud compatibility

Redis
Enterprise
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

  • If GET was not specified, one of the following:
    • Null bulk string reply in the following two cases.
      • The key doesn’t exist and XX/IFEQ/IFDEQ was specified. The key was not created.
      • The key exists, and NX was specified or a specified IFEQ/IFNE/IFDEQ/IFDNE condition is false. The key was not set.
    • Simple string reply: OK: The key was set.
  • If GET was specified, one of the following:

History

RATE THIS PAGE
Back to top ↑

AltStyle によって変換されたページ (->オリジナル) /