This is the 9th day of my participation in the August Wen Challenge.More challenges in August
The introduction
Redis is a DATABASE in K/V mode for daily development when there is a problem with a frequently accessed service
We should first consider whether we can use Redis cache optimization. Why? Because Redis is completely memory based, it is very fast to read and there are only a few data structures. Reading databases comes quickly and conveniently to cluster…. Today, we’ll take a closer look at the redis cache
The body of the
When to use caching
- When some of our apis are infrequently updated and accessed.
- Very time-consuming query results can be stored in Redis
- Counters, distributed locks, leaderboards…
Simple application
2.1 the String
Don’t be fooled by the type name. Strings don’t just store strings. We can store things like byte, long, double, and even objects we can serialize. For example: we want to cache a User data
static void Main(string[] args)
{
using var conn = ConnectionMultiplexer.Connect("localhost,allowAdmin=true,abortConnect=false,connectTimeout=2000");
var db = conn.GetDatabase();
var user = new User { Name = "Luo Xiang said criminal law.", Uid = "517327498", Subscribers = "1698w" };
string key = $"user:{user.Uid}";
db.StringSet($"user:{user.Uid}", JsonSerializer.Serialize(user));
var value = (string)db.StringGet(key);
Console.WriteLine(value);
}
Copy the code
This is done by serializing the User object as a Json string and storing it in the key as a string
Tips: When generating key names, be sure to use a certain style. For example, user: XXX is used as a key so that you can later use keys or scan to find all users. By the way, using MessagePack or Bson can make the stored string smaller
2.2 the HASH
The HASH type is useful when storing a set of associated data, such as the number of visits to each page. You can draw up the following Hash structure:
Then record the daily count to SQL, so you don’t have to worry about changing the data too many times.
2.3 the Set
This type is suitable for non-repetitive data, such as the data in the navigation bar of station B (if the data is configured in the menu).
The cluster
In order to improve the performance of redis single machine, we can use cluster optimization (updated later).