Interviewer: Let's talk about Redis, answer as much as you know

Hello! Hello everyone, I'm Xiaoqi, an unreliable programmer.
Xiaoqi intends to share some techniques in a relaxed and humorous way. If you think you have learned something through Xiaoqi's article, then give Xiaoqi a like.
The article is continuously updated, you can search for [Xiaoqi JAVA Interview] on WeChat to read it as soon as possible, and reply to [Information] and there are more benefits I have prepared for you!

I. Introduction

As a Java programmer, some of the underlying principles of Redis are a skill point that we can move bricks without having to learn , but why does Xiaoqi talk about it? Is it just to waste 1 minute of everyone 's precious time, 1 minute for one person, 500,000 people is 1 year , 50 million people is 100 years , earning, Xiaoqi successfully hooked up with one person (blood earning).

Of course not, and Xiaoqi's article is not read by so many people, so it's a waste of a kidney at most .

Learning the underlying principles of Redis is because the interviewer wants to ask ! , so we have to learn, what? You don't learn if it's not practical? That neighbor, Xiaoqi, is going to study hard, and the interviewer only wants Xiaoqi not to want you.
insert image description here

As for why you asked why the interviewer asked about the underlying principles of Redis, this. . . I leave this opportunity to you. Next time you interview, the interviewer asks: "Tell me about the underlying principles of Redis". You: "Hello, interviewer, why are you asking about the underlying principles of Redis? You give me a computer, and I 'll set up a library management system for you in five minutes . Isn't it delicious? Let's see the real chapter on the keyboard." At this time, the interviewer will tell you the answer, you can type the answer in the comment area, and let Xiaoqi and many friends know why you are asking?

insert image description here

2. Interview

On a sunny Sunday, I came to an unfamiliar park (don't ask why it's a Sunday, it's 997, but in order to fill the stomach of migrant workers, I can only know that there are tigers in the mountains, and I tend to walk in the mountains), sitting in the unfamiliar In the conference room, I was waiting for Miss HR to call the interviewer. At this time, my mood was as mixed as your friends. I was worried that it would be difficult for the interviewer to ask? What should I do when asked about my knowledge blind spot? When I introduce myself for a while, do you want to talk about my relationship with Xiaoqi?

A handsome interviewer with sharp eyes walked in and saw his sharp eyes that seemed to be able to see through everything. I was thinking, otherwise I would not want 20k for a while, but 8k. It's so confusing, but I remembered that I just watched Xiaoqi's fun learning programming series before I came. I have completely learned the essence of Xiaoqi. I immediately got the confidence and decided to ask for 30k for a while, and learn Xiaoqi if I don't give it. Don't go (haha)

Interviewer: Xiaoqi, right, have you brought your resume?

Me: I didn't bring it. Now I have two pieces for color printing, and five resumes for me. Each interview costs ten dollars. My friend said that you should not go to a job that requires you to pay before you get a job.

Interviewer: . . . Then what do you rely on to conquer me and let me hire you

Me: Temperament?
Please add image description

(At this time, the interviewer did not call the security guard, but took out the stick that had been waiting for me for a long time from behind the door, and I was instantly cowardly)

insert image description here

I had to take out from my backpack the resume I asked for from other company interviewers in the morning, and this is the situation in the morning.

Interviewer in the morning: That's it for today's interview, go back and wait for the notice!

Me: Hello interviewer, if your company does not plan to admit me, can you return my paper resume to me? I have another interview in the afternoon.

The interviewer in the morning: I said why your resume is wrinkled, it turns out that you have been recycling it! How long has this symptom been present?

Me: It 's been half a month . . .

(The interview went on after I handed my crumpled resume to the interviewer...)

3. Redis basic data types and usage scenarios

Interviewer: I see that you are proficient in Redis on your resume? (Hmph, the interviewer smiles contemptuously)

(Looking at the interviewer's contemptuous smile, I couldn't help but take out my Redis book and push it to him)

Me: I have recited this book by heart. If you ask any question, if you can’t answer it, I will be considered a loser. If you answer it, you must apologize to me for your contempt.

insert image description here

(My smile gradually becomes more confident...)

insert image description here

(The interviewer is looking at the book thoughtfully at this time, I suspect he must be thinking about how well he knows the book)

Interviewer: Well, let’s briefly talk about what data types Redis has.

Me: redis mainly has five data types, namely String, Hash, List, Set, and ZSet .

Interviewer: Then how do they store and read data, and what are the usage scenarios?

1、String

Single value storage: set [key] [value]
insert image description here
Value: get [key]
insert image description here

Multi-value storage: mset [key1] [value] [key2] [value]
insert image description here
Value: mget [key1] [key2]
insert image description here

Distributed lock lock: setnx [key] true

returns 1 for successful locking and
insert image description here
0 for failed
insert image description here
lock release Distributed lock release lock: del [key]
insert image description here
Set timeout: expire [key] [time] (if an exception occurs, it will be deleted If the lock fails, you can set a timeout period, and the lock will be automatically deleted when the time arrives.) To
insert image description here
achieve atomic distributed lock locking and set the timeout period: set [key] true ex [time] nx (if the lock is completed within the timeout period for the lock If an exception occurs, the lock cannot be deleted, so combine the lock command and the timeout command into one command)
insert image description here

Counter: incr[key]
insert image description here
Get the value of the counter: get [key]
insert image description here
Get the count in batches: incrby[key]
insert image description here
Get the value of the counter: get [key]
insert image description here

2、Hash

Store data: hset [table] [key] [value] (here we can assume the implementation of adding items

to the shopping cart) Add an apple
insert image description here
to the shopping cart Add a book
insert image description here
to the shopping cart Add a banana to the shopping cart
insert image description here

Add quantity to the original item: hincrby [table] [key] [quantity]

and add an apple to the shopping cart
insert image description here

Number of product types: hlen [table]
insert image description here

Get all items in the cart: hgetall [table]
insert image description here

Delete item: hdel [table] [key]
insert image description here

3、List

Put a value into the head (leftmost) of the list: lpush [key] [value]
insert image description here

Remove and return the head element of the list: lpop [key]
insert image description here

Put a value at the end of the list (rightmost): rpush [key] [value]
insert image description here

Remove and return the tail element of the list: rpop [key]
insert image description here

Returns the elements in the specified range in the list: lrange [key] [start position] [end position]
insert image description here

Pop an element from the head of the list. If there is no element in the list, block and wait for time seconds. If time=0, block and wait for
insert image description here
an element to be popped from the end of the list. If there is no element in the list, block and wait for time seconds. If time=0 , has been blocking waiting
insert image description here

4、Set

Store an element into the set key, ignore the element if it exists, and create a new one if the key does not exist: sadd [key] [element] (Here we imitate a lottery business scenario, and first put the person to be drawn into the set)
insert image description here

Randomly select several elements from the set key, and the elements are not deleted from the set: srandmember [key] [number of elements] (here we draw two awards)
insert image description here

Get all elements in the set key: smembers [key]
insert image description here

Get the number of elements in the set key: scar [key]
insert image description here

Determine whether an element exists in the set: sismember [key] [element]
insert image description here

Remove element from set: srem [key] [element]
insert image description here

Randomly select a few elements from the set and delete: spop [key] [number of elements] (For example, when we draw the third prize first, then the third prize is not eligible when we draw the second prize , the third prize winner will be deleted)
insert image description here

Intersection operation: sinter [key] [element]
insert image description here

Store the intersection result in a new set key2: sinterstore [key2] [key] [element]
insert image description here

Union operation: sunion [key] [element]
insert image description here

Store the union result in a new set key2: sunionstore [key2] key [element]
insert image description here

Difference operation: sdiff [key] [operation]
insert image description here

Store the difference result in the new set key2: sdiffstore [key2] [key] [element]
insert image description here

5 、 ZSet

Add an element with a score to the ordered set key: zadd [key] [score] [element] (In business, we can use it to achieve functions such as Weibo hot search ranking)
insert image description here

Returns the score of the element in the sorted set key: zscore [key] [element]
insert image description here

Returns the number of elements in the sorted set key: zcard [key]
insert image description here

Add a score to the score of an element in the sorted set key: zincrby [key] [score] [element]
insert image description here

Get the elements of the sorted set key from the start index to the end index in positive order: zrange [key] [start] [end]
insert image description here

Get the elements of the ordered set key from the start subscript to the end subscript in flashback: zrevrange [key] [start subscript] [end subscript] (here, for example, in the Weibo hot search list, the top ten are obtained in flashback order by popularity)
insert image description here

Remove an element from the sorted set key: zrem [key] [element]
insert image description here

(It is not easy to organize, sexy Xiaoqi asks for praise online...)

insert image description here

Fourth, Redis daily problems

Interviewer: Hmm. You have written so much above that I can't even bother to read it, so I'll just ask you a few questions.

I'm good

Interviewer: How do we create distributed locks in Redis

me: use setnx command

Interviewer: After creating a distributed lock in Redis, there is an abnormal unlock failure, how to delete this lock

Me: You can use expire to add a time to the lock, after which Redis automatically deletes the lock.

Interviewer: What if an exception occurs before the time is added and the time is not added?

Me: You can use atomic commands to create distributed locks and time together, so you don't have to worry about exceptions, because of atomicity, one success succeeds, and one failure fails.

insert image description here

Interviewer: Is Redis single-threaded?

Me: Redis is single-threaded when reading and writing operations, but other functions, such as persistence, asynchronous deletion, cluster data synchronization, etc., are executed by additional threads.

Interviewer: Why is Redis single-threaded so fast?

Me: Because Redis data is all in memory, and single thread avoids the problem of multi-thread switching performance loss.

Interviewer: How does Redis single thread handle concurrent client connections?

Me: Redis uses epoll to implement IO multiplexing , putting connection information and events into the queue, and then placing them in the file event dispatcher in turn, and the event dispatcher distributes the events to the event handler.

insert image description here

Interviewer: How do I query all keys in Redis in full, or how to query keys that meet the rules in a fuzzy query?

Me: Use keys * to query all keys in Redis. If you want to fuzzy query, you can directly add rules. For example, if you want to query keys with a prefix of Xiaoqi, you can use keys Xiaoqi* to query

Interviewer: Is there any problem with this query? Is there any other solution?

Me: The use of keys * query is to fully query the key values ​​in Redis. If there are too many key values, the thread will block the most. Because Redis read and write is single-threaded, we can use the scan command to read data incrementally.

Interviewer: Can you elaborate on the scan command?

I: The format of the scan command is: scan [cursor] match [wildcard] count [the number of each query] (the cursor is 0 in the initial query, and then the cursor in the second query is the data returned in the first query, in turn By analogy, when the cursor returns 0 at the end, the query is completed.)

I now have a total of 9 pieces of data in Redis, and I query 3 pieces each time, and the query is completed in three times.
insert image description here

Interviewer: Are there any drawbacks to the scan command? Is it sure to obtain the full amount of data?

Me: Not necessarily, if there are new data changes in the process of scan, such as inserting data, deleting data, etc., then the newly added keys may not be traversed, because the place that scan has traversed is no longer traversed, you insert to traverse The places you have passed will not be traversed again.

insert image description here

Interviewer: This guy is amazing, I don't have anything to ask here, what more questions do you have to ask (the interviewer's eyes are shining)

me: uh. . . Can the interviewer give me my paper resume? Can I not write and draw on my resume? I will use it for my interview tomorrow.

Interviewer: What other companies are you looking for? Just come to me. The conditions are open to you.

Me: 100k then (at this time the interviewer picked up the stick he prepared again)

Interviewer: If you don't come, give me a recommendation and let someone else come to me for an interview

Me: You should study Redis first. Fortunately, I am the only one here today. If Xiaoqi's loyal readers come, you will be abused miserably. (I left my "Redis Design and Implementation" to the interviewer, turned around and left a handsome back, and the interviewer sat there blankly, as if a hundred million had left him...)

V. Summary

The information about Redis here has not been sorted out, and the article will continue to be updated later. It is recommended to collect it.

The commands involved in the article must be knocked several times like me. Only in the process of knocking can you find out whether you really master the commands.

If you think my article is not bad, please like it. In addition, you can search [Xiaoqi JAVA Interview] on WeChat to read more good articles and get the information I have prepared for you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324146318&siteId=291194637