String and Hash

Learn the basics of string and hash and how to execute their operations using the go-redis client.

String

A string is one of the simplest data types, which makes it a good starting point to learn Redis. Despite its simplicity, it’s quite versatile. It can be used to cache a simple value for a key or a complex result of a SQL query. In addition to this, it can also be used for bitwise operations and as atomic counters.

Note: By default, the maximum size of a Redis string value is 512 MB.

Let’s go over some of the common String operations.

  • Set

  • Apply Time-to-Live (TTL)

  • Incr, IncrBy

  • SetArgs

  • GetRange

Set

We can set a key to a string value. In this example, the key foo is set to the value bar using the Set method.

client.Set(ctx, "foo", "bar", 0).Result()
Set a key to a value

Time-to-Live (TTL)

We can also set a Time-to-Live (TTL) for a specific key, after which Redis deletes it automatically. Here, key foo1 is set to bar1 with a TTL of two seconds (after which it expires). If we try to fetch its value after two seconds, it will no longer be available.

client.Set(ctx, "foo1", "bar1", 2*time.Second).Result()
time.Sleep(3 * time.Second)
_, err = client.Get(ctx, "foo1").Result()
if err != nil {
if errors.Is(err, redis.Nil) {
log.Println("foo1 expired")
}
}
Specify Time-to-Live for a key

Note: If a TTL is not provided, by default, a key in Redis won’t expire. ...