This is my first time to use Redis, really. Because the company is small and the business volume is small, Redis is not useful at all. Recently, however, I plan to upgrade the system to bring in the latest technology, albeit a little late (note the quotes).
As a responsible technical blogger, I feel it is necessary to share my process of getting into Redis for some friends to refer to. If I write where wrong, feel free to come to give me a slap, just (gentle point, don’t hit swollen, affect the appearance level is not good).
01, What is Redis
Redis, the most widely used storage middleware in Internet technology, is a combination of bold letters in three words: Remote Dictionary Service. Don’t say it. It sounds natural when you put it together.
Redis is known for its super high performance, perfect documentation and simple source code. Many large Internet companies at home and abroad are using it, such as Ali, Tencent, GitHub, Stack Overflow and so on. It is getting more and more powerful. It was originally used as a cache database, but now it can be used to implement message queues.
Suffice it to say, mastering Redis has become a basic skill that back-end engineers must have.
The author of Redis is an Italian who goes by the screen name Antirez and looks pretty good. If you are interested, Google it. Know why the default port of Redis is 6379?
It is said to be determined by the position of “MERZ” on the keypad, so you can open the nine-grid keypad on your phone to feel it. What does “MERZ” mean? It is said to mean “stupid”. This? Do you feel there is a lot of mystery in programmer’s life?
02. Install Redis
Redis has different installation methods for different operating systems, and we’ll use Windows as an example for this introductory article.
Download address:
Github.com/MicrosoftAr…
The latest version of Windows is 3.2.100. As you can see from the image below, Redis is very lightweight, less than 6 meters. The smaller the Redis, the better I feel. Do you feel the same way?
There are two ways to install, the first is the MSI way, double-click the installation; The second is install-free, green version, which simply unzip the ZIP package.
There is an English version of Windows Service Document.docx that tells us how to install the Redis Service, how to start it, how to shut it down, and how to start it using a custom port.
Open the command line, go to the current decompressed directory, and enter the startup command:
redis-server redis.windows.conf
Copy the code
Then you will see the welcome screen after Redis launches. The box on the left feels so artistic! Any of you know how it’s made?
Here are some other tips:
- The current version of Redis is 3.2.100
- Port is 6379
- The process ID, or PID, is 12636
- The official Redis address is http://redis.io
So how do you stop service? You can directly press Ctrl+C – rough, wall dong (of course you can directly click the cross in the upper right corner).
PS: ORIGINALLY wanted to use Linux version or OSX version, afraid of the introduction of small partners without environment. We can do one in the back.
03. Data structure of Redis
Redis has 5 basic data structures, String, Hash, List, Set, SortedSet, is also learning Redis must master. In addition, there are HyperLogLog, Geo, Pub/Sub, which are advanced data structures. Let’s use String as an example for this introductory article.
The String structure is widely used, such as converting the user’s login information into a JSON String and caching it, and deserializing it when it needs to be retrieved.
As you know, Java strings are immutable and cannot be modified. Redis String is dynamic and modifiable. As for the String structure of Redis, I think Mr. Qian’s Redis tutorial is very clear, we read it together.
Redis String is similar to Java’s ArrayList in its internal structure, in that it preallocates redundant space to reduce frequent memory allocation. As shown in the figure above, the actual space allocated to the current string is Capacity, which is generally higher than len. If the string length is less than 1 MB, the capacity expansion multiplies the existing space. If the length exceeds 1 MB, capacity expansion only adds 1 MB space. The maximum length is 512 MB.
04, practical operation Redis
All right, all right. I’m sure a lot of you guys are ready to go. This with you.
There is a file named redis-cli.exe in the decompression directory of Redis, which is a client tool of Redis, which can be used to connect to the Redis service we started before. Double-click to start it.
The client is also very intelligent, when typing commands, will pop up the corresponding prompt
When you press the space to follow the keyword, the prompt in the corresponding position will disappear automatically.
The following is a complete set of key/value pair test commands that you can use to test them.
> set name cmower
OK
>get name
"cmower"
>exists name
(integer) 1
>del name
(integer) 1
>get name
(nil)
Copy the code
1) The set command is used to store a key-value pair. In this case, name is the key and Cmower is the value.
2) The get command is used to obtain a key/value pair.
3) The exists command tests whether a key-value pair exists. (integer) 1 indicates that a key-value pair exists, and (integer) 0 indicates that a key-value pair does not exist.
4) Using the del command, you can delete a key-value pair. (integer) 1 indicates that the execution succeeds, and (integer) 0 indicates that the execution fails.
5) When the key-value pair is deleted and then retrieved by get, the result is (nil).
Some of you might be wondering, what does nil mean? It is a keyword in Programming languages such as Objective-C, Swift, Ruby, Lua, etc. For a more detailed explanation, see Programming in Lua 2nd Edition:
Nil is a type, it has only one value nil, and its main function is to distinguish it from any other value. As I said before, the default value of a global variable before the first assignment is nil. Assigning nil to a global variable is equivalent to deleting it, Lua uses nil for a “non-value” situation, where there are no valid values.
For details on how to use the Redis command, see the following link:
redisdoc.com/index.html
Redis Documentation – Redis Command Reference – Redis Documentation – Redis Documentation
05. Use Redis in Java
Some people may ask, “Brother, I am a Java programmer, how do I use Redis in Java?” That’s a good question. I’m on my way. I’m on my way.
First, add Jedis (Java/Redis mashup) dependencies to your project:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
Copy the code
Step 2: Create a new UserInfo class:
public class UserInfo {
private String name;
private int age;
public UserInfo(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString(a) {
return "UserInfo{" +
"name='" + name + '\' ' +
", age=" + age +
'} ';
}
// getter / setter
}
Copy the code
Third, add Gson (for serializing and deserializing user information) dependencies to the project:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
<scope>compile</scope>
</dependency>
Copy the code
Step 4 create a new test class RedisTest:
public class RedisTest {
private static final String REDIS_KEY = "user";
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost".6379);
Gson gson = new Gson();
UserInfo userInfo = new UserInfo("Silent King II.".18);
jedis.set(REDIS_KEY, gson.toJson(userInfo));
UserInfo getUserInfoFromRedis = gson.fromJson(jedis.get(REDIS_KEY),UserInfo.class);
System.out.println("get:" + getUserInfoFromRedis);
System.out.println("The exists." + jedis.exists(REDIS_KEY));
System.out.println("del:" + jedis.del(REDIS_KEY));
System.out.println("get:" + jedis.get(REDIS_KEY));
}
}
Copy the code
1) REDIS_KEY constant is the key that stores user information to Redis.
2) With the help of Jedis, Java connecting to the Redis service is as simple as one line of code:
Jedis jedis = new Jedis("localhost".6379);
Copy the code
The parameters are host name and port number.
Set () is used to store key-value pairs, get() is used to obtain key-value pairs, exists() is used to determine whether key-value pairs exist, and del() is used to delete key-value pairs.
3) Gson is an open source library provided by Google that serializes Java objects into JSON strings, as well as deserializing (parsing) JSON strings into matching Java objects.
The toJson() method converts an object to a JSON string, and the fromJson() method deserializes an object from a JSON string.
Ok, let’s look at the output of the program:
get: the UserInfo {name ='The Silent King ii', age=18}
The exists:true
Del:1
get:null
Copy the code
Exactly what we expected, Perfect!
06, thanks
Ok, my dear friends, the above is all the content of this article, if you want to practice Redis after reading it, hurry up! If you have any problems in the process of learning, please feel free to communicate with me. Although I am a rookie, I am enthusiastic.
Also, if you want to write an entry level article, this is the perfect example.
I am silent King 2, an interesting programmer. If you think this article is helpful to you, please search “Silent King ii” on wechat to read it for the first time, and reply to “Redis” with a mysterious material.
Interview on GitHub
Original is not easy, do not want a free ticket, please point a praise for this article, it will be the strongest power FOR me to write more high-quality articles.