String and Hash
Explore key Redis string and hash data types and how to manipulate them using Go. Understand common operations such as Set, Get, IncrBy for strings, and HSet, HGet, HMGet for hashes to effectively manage data in your applications.
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.
SetApply Time-to-Live (TTL)
Incr,IncrBySetArgsGetRange
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()
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")}}
Note: If a TTL is not provided, by default, a key in Redis won’t expire.
The Incr and IncrBy operations
If the value contains a string that can be ...