How Should Redis be used ?, Redis exploitation?

Source: Internet
Author: User

How Should Redis be used ?, Redis exploitation?

Redis is a good thing. After two weeks of research and practice, the original local memory cache is largely replaced in the project. However, during the replacement process, we found that Redis is a high-end and atmospheric class, which does not seem to be the method I imagined.

Before going into Redis, in my concept, cache is key-value. The usage method certainly does not need to change much code, and everything is Get/Set. However, in actual use, I found that not all scenarios are simple Get/Set. Not all data is suitable for key-Value. So how can we use Redis? I asked myself and asked my friends in the garden for help. Of course, this article will introduce you to my insights over the past two weeks.

Use Cases

One of my projects is providedThe Autocomplete function has tens of thousands of data records. In this article, I use the name search example to describe the list. Please stamp the Demo from the author of Redis.

In this list, all are 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;}    }

A user's drop-down list is required in the system. The AutoComplete function is added because a large amount of data cannot be displayed at a time. If a centralized cache like Redis is not used and is directly cached in the local memory, the structure is as follows:

Var users = new List <User> {...}; // read a user list named MemoryCache. set ("capqueen: users", users); // put it into memory // read var users = MemoryCache. get <List <User> ("capqueen: users ");

Because they are all in the memory, you can store the List directly. You can also directly search the List as follows:

Var findUsers = users. Where (user => user. Name. StartWith ("A"). ToList (); for example, the input character is "A"

 

It is quite simple. You don't have to consider how to store and store the data structure. But after changing to the Redis centralized cache service, let's think about how to store it.

Solution 1: similar to 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 (); // get 0 database var usersJson = JsonConvert. serializeObject (users) // serialize the database. stringSet ("capqueen: users", usersJson); // store var usersString = db. stringGet ("capqueen: users"); var userList = JsonConvert. deserializeObject <List <User> (users); // deserialization

The above method is logically correct and can be compiled. But think about it carefully. Redis, as an independent cache service, is isolated from appSever. Such reading method is a burden on redis server IO, the read speed is much slower than the local memory cache.

How can this problem be solved? Imagine that the essence of key-value is the Key. For List, items should be stored separately.

Solution 2: Keys fuzzy match.

After checking the Redis command documentation (see reference 4), we found the command Keys. If we were lucky, we immediately modified the solution. First, we need to set the keywords to be searched as keys. Here I define the key as "capqueen: user: {id }:{ name }", the items in {} must be replaced by the corresponding item attribute. 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);});

Shows the created cache:

All users are stored in separate Key-Value mode. How can we use Keys to search? Let's take a look at the Redis Keys command:

KEYS pattern searches for all KEYS that match the specified pattern. KEYS * matches all KEYS in the database. KEYS h? Llo matches hello, hallo, and hxllo. KEYS h * llo matches hllo and heeeeello. KEYS h [AE] llo matches hello and hallo, but does not match hillo. Special symbols are separated \

 

That is to say, Keys can perform simple fuzzy match, so we can use the following method to search here:

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 (); // deserialize var jsonValues = new StringBuilder ("["); values. toList (). forEach (item => jsonValues. append (item ). append (","); jsonValues. append ("]"); var userList = JsonConvert. deserializeObject <List <User> (jsonValues. toString ());

Note that in the above Code, because each value is a json, in order to increase the conversion efficiency, I first process it into json arry before deserialization.

This solution does solve my current problems, but I have noticed a passage in the Redis document:

KEYS is very fast, but using it in a large database may still cause performance problems. If you need to find a specifickey, You 'd better use the Redis set structure instead.

In other words, it means to use Keys search with caution. So what is a better solution? I have been dragging on this article for a long time. I am very grateful to you for leaving a question at the end. Of course, there is another article. I will talk about my current solution.

 

In the next article, I will create a new solution based on the practices in the blog (document 1) of the author of Redis and the last materials I have found. Please advise.

References

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.