How to use Redis
Usage scenarios
In my project, there is a function provided for Autocomplete, and the amount of data is probably tens of thousands. In this article, I use the example of name retrieval to illustrate. For the list, please click on the Demo from the author of Redis.
Such a list is full of user names. For example, there is a user object in our system:
public Class User
{ public string Id{get; set;}
public string Name {get; set;}
.... public string UserHead {get; set;}
}
The system needs a drop-down list of users, which cannot be done due to the large amount of data. It is displayed once, so an AutoComplete function is added. The cache can be stored directly in local memory. There is no need to use a centralized cache like Redis, so the cache structure will be simpler.
var users = new List<User>{...};//读到一个用户列表MemoryCache.Set("capqueen:users", users);//放入内存//读取var users = MemoryCache.Get<List<User>>("capqueen:users");
Because they are all in memory, it is enough to store the List directly. When searching It can also be directly as follows:
var findUsers = users.Where(user => user.Name.StartWith("A")).ToList();例如输入的字符是 “A“
It is quite simple. There is no need to consider how to store and the stored data structure. However, once we move to a centralized caching service like Redis, we need to rethink how we store it.
Option 1: Similar memory-based cache implementation.
The Redis link library used in this article is StactkExchange.Redis, an open source product from StackOverFlow.
var db = redis.GetDataBase();//获取0数据库var usersJson = JsonConvert.SerializeObject(users)//序列化db.StringSet("capqueen:users", usersJson);//存储var usersString = db.StringGet("capqueen:users");
var userList = JsonConvert.DeserializeObject<List<User>>(users);//反序列化
There is no logical problem with the above method, and the compilation can pass. But if you think about it carefully, Redis is an independent cache service and is separated from appSever. This kind of reading method is a burden on the IO of the redis server, and even such reading is much slower than the local memory cache.
How to solve it? Just imagine that the essence of key-value lies in Key, so for List, items should be stored separately.
Option 2: Keys fuzzy matching.
After browsing the Redis command documentation (see Reference 4), he was surprised to find the Keys command, which made him immediately modify his plan. First, we need to establish the keyword to be searched as a key. Here I define the key as "capqueen:user:{id}:{name}", where the items in {} need to be replaced with the corresponding attributes of the item. The code is as follows:
var redis = ConnectionMultiplexer.Connect("localhost");var db = redis.GetDatabase();
var users = new List<User> { new User{Id = 6, Name = "aaren", Age=10}, new User{Id = 7, Name = "issy", Age=11}, new User{Id = 8, Name = "janina", Age=13}, new User{Id = 9, Name = "karena", Age=14}
};
users.ForEach(item => {
var key = string.Format("capqueen:user:{0}:{1}", item.Id, item.Name); var value = JsonConvert.SerializeObject(item);
db.StringSet(key, value);
});
All users are stored in separate Key-Value methods, so how to use Keys to search? Let’s take a look at the Keys command of Redis:
KEYS pattern 查找所有符合给定模式 pattern 的 key 。 KEYS * 匹配数据库中所有 key 。 KEYS h?llo 匹配 hello , hallo 和 hxllo 等。 KEYS h*llo 匹配 hllo 和 heeeeello 等。 KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo 。 特殊符号用 \ 隔开
In other words, Keys can perform simple fuzzy matching, so our search here can be changed to the following method:
var redis = ConnectionMultiplexer.Connect("192.168.10.178");var db = redis.GetDatabase();var server = redis.GetServer("192.168.10.178", 6379);var keys = server.Keys(pattern: "capqueen:user:*:a*");var values = db.StringGet(keys.ToArray());//反序列化var jsonValues = new StringBuilder("[");
values.ToList().ForEach(item => jsonValues.Append(item).Append(","));
jsonValues.Append("]");var userList = JsonConvert.DeserializeObject<List<User>>(jsonValues.ToString());
Note the above In the code, because each value is a json, in order to increase the efficiency of conversion, I first process it into json arry and then deserialize it.
This solution indeed solved my current problem. However, I noticed a passage in the Redis document:
KEYS is very fast, but when used in a large database It may still cause performance problems. If you need to find a specific key from a data set, you are better off using Redis's set structure (set) instead.
The above is the detailed content of How to use Redis. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1793
16
1736
56
1587
29
267
587
Laravel8 optimization points
Apr 18, 2025 pm 12:24 PM
Laravel 8 provides the following options for performance optimization: Cache configuration: Use Redis to cache drivers, cache facades, cache views, and page snippets. Database optimization: establish indexing, use query scope, and use Eloquent relationships. JavaScript and CSS optimization: Use version control, merge and shrink assets, use CDN. Code optimization: Use Composer installation package, use Laravel helper functions, and follow PSR standards. Monitoring and analysis: Use Laravel Scout, use Telescope, monitor application metrics.
How to use the Redis cache solution to efficiently realize the requirements of product ranking list?
Apr 19, 2025 pm 11:36 PM
How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...
What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?
Apr 19, 2025 pm 08:03 PM
In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...
Recommended Laravel's best expansion packs: 2024 essential tools
Apr 30, 2025 pm 02:18 PM
The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.
Laravel environment construction and basic configuration (Windows/Mac/Linux)
Apr 30, 2025 pm 02:27 PM
The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.
Redis's Role: Exploring the Data Storage and Management Capabilities
Apr 22, 2025 am 12:10 AM
Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.
In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node?
Apr 19, 2025 pm 10:57 PM
The optimization solution for SpringBoot timing tasks in a multi-node environment is developing Spring...
Redis: Understanding Its Architecture and Purpose
Apr 26, 2025 am 12:11 AM
Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.


