table of Contents
- 1. Why learn Redis?
- Two, Redis installation
- Three, Redis basics
- 3.1 Redis is single-threaded
- 3.2 The five common data types and related commands
- 3.2.1 Basic commands of RedisKey
- 3.2.2 Five commonly used types
1. Why learn Redis?
When we learn a new thing, we must first understand why we learn it? That is, what problems can Redis solve. We can draw a picture and explain step by step.
First, the client will send a large number of user requests to the server. If a single server cannot accept such a large request, a server cluster needs to be configured. For example, a large number of servers will be added on Double Eleven.
Increasing the server can solve the problem of excessive client requests, but there is also a problem, that is, the pressure on the database is too large, and if some data commonly used by users is checked in the database every time, it is also very time-consuming, so For frequently operated hot data, it is placed in Redis. Redis is based on memory to store data and read data, supports high concurrency, performance is very good, and the efficiency is much faster than reading data in MySQL. And there are some problems with the server, that is, if the session was used to store data in the past, because the server is a cluster, the first session saved is placed on server 1, but the next time the request is random, the previously saved session may not be available. It is to find on another server. With Redis, this problem can be solved by putting it in Redis. Including the operation of locks, clusters cannot achieve mutual exclusion. If one server can work, multiple ones can't. Redis is single-threaded to receive user requests to achieve the effect of this kind of lock. The above is why Redis is used, which is the problem it can solve.
Summarize the problems that Redis can solve:
1. The amount of users is too large, the requests are also large, and the database pressure is heavy.
2. The data is not synchronized between multiple servers, which is the problem of session data storage.
3. There is no mutual exclusion of locks between multiple servers
Redis has so many benefits and can solve so many problems, so let's learn it! ! !
Two, Redis installation
A brief introduction to Redis
Redis ( Re Mote Di ctionary S erver- remote service dictionary) is a non-relational database (NoSQL-> Not Only SQL), is based on the Key-Value NoSQL, written in C language, and have persisted, not because The database is abnormal, crashed or loses data after a power outage. In fact, non-relational databases include ElasticSearch and Mongodb. Let's install them now.
Learn more about Redis link: http://www.redis.cn/
Redis recommends setting up and installing on Linux. Windows has been stopped for a long time and is slow. Basically, it is operated on Linux. You can download the installation package on the homepage. It is a redis package installed on Linux
. When I downloaded it, it was really slow, only 2,1M in total. Here is a link to download the redis 6.0.8 version of the Baidu network disk shared by a blogger
Download it and drag it directly into MobaXterm. The following blog installation is very detailed and very nice, just follow the installation
butnoteInside redis.conf, one or two are written as redis.config, this should be noted, do not copy its redis.config, write redis.conf, I said in the blogger’s comment area, I don’t know if I can see it .
Test performance (additional understanding)
Suppose we want to test, 100 concurrent connections with 100,000 requests, look at the performance, redis-benchmark is used to test the performance.
First, if you don’t start redis, you need to start the connection first.
redis-server rconfig/redis.conf redis-cli -p 6379
The test command is as follows
redis-benchmark -h localhost -p 6379 -c 100 -n 100000
This is a stress test, as long as we understand it, we just need to do it again.
Three, Redis basics
3.1 Redis is single-threaded
Is Redis fast multi-threaded? No, Redis is single threaded! ! !
Why is Redis so fast with single thread? ? ?
(1) Most of Redis requests are pure memory operations, which are very fast. It is not based on CPU.
(2) It uses single thread to avoid unnecessary context switching and race conditions, because multi-threaded CPU requires context switching. Cost and overhead
Redis has 16 databases. The default is 0.
There is no data set initially. After setting key value, there will be a value. If we switch to another database, such as 2, it will be empty, that is, each database is independent.
keys *You can view all the keys in the database, get key can get the value value (I am wrong in the above picture,  should indicate the fourth database)
flushdb #清除当前数据库数据 flushall #清除全部数据库（慎用）
3.2 The five common data types and related commands
3.2.1 Basic commands of RedisKey
Let me talk about some commands first, and then the 5 major types. I
have talked about the common ones before
set key value，get name，keys *, and there are some commands as follows
EXISTS KEY #有对应值会返回1，否则返回0 move key 1 #将key从当前数据库移动到指定数据库 del key #删除key EXPIRE key 时间 #设置key什么时候过期，如EXPIRE name 10表示name10秒后过期，14天免登录可以用 ttl key #key还剩多久过期，-2表示已过期 type key #查看key的类型
You can also search on the official website if you want related commands in the future
3.2.2 Five commonly used types
If there is a database before,
flushdbdelete all and recreate
append key 追加内容 #给key追加内容，key不存在就相当于set创建，存在则追加 strlen key #查看key对应value的长度 incr key #+1 dece key #-1 incrby key 增量 #如incrby num 10就是每次执行+10 decrby key 减量 getrange key index1 index2 #截取key setrange key index 替换的内容 #从index位置替换，即替换指定位置开始的字符串 setex key 时间 value #设置时间期限创建key setnx key value #key不存在才能创建，存在就创建失败 mset key1 value1 key2 value2 ... #同时设置多个值 mget key1 key2 #同时取多个值 msetnx key1 value1 key2 value2 #不存在时创建，这是原子性操作，要么同时创建成功，要么失败，有一个失败都
Redis is often used to increase the reading volume, such as the reading volume of CSDN, you can use this, check it, and automatically increase the 1
getset key value #如果key没有设置，那么get返回为空，然后再set值，已经有值会先返回get的值，然后set新的value
(2) The List
list is as shown in the figure below, the
flushdbdatabase before clear
flushdbclear the database first , and then play List
lpush key value #向列表中push值，有点像栈 lrange key 0,-1 #表示获取所有值，0 1就是l取两个值
Here key generally writes list to indicate that the list
lpush is the push on the left, and rpush is the push from the right, which means that
values can be inserted from both sides. If it can be inserted, then it can be deleted.
lpop key #返回出列表的元素 rpop key lindex key 下标 #从左边查找元素，从0开始 llen key #返回列表长度 lrem key 移除数量 value #移除固定的值 ltrim key 下标1,下标2 #截取 lset key 下标 替换的值 #替换某一个元素
Trim is pruning, it will modify the previous list, just like cutting a branch, it will cut a part, and leave a part.
The following corresponds to the update operation
rpoplpush 列表1 列表2 #列表1右端第一个移动到列表2的左边 linsert key before/after 元素1 元素2 #将元素2插入到元素1的前面或者后面
Insertion or modification on both sides is the most efficient, the efficiency will be much lower in the middle, stack (Lpush Lpop), queue (Lpush, Rpop)
The value in Set Set cannot be repeated, as in Java, the
flushdbprevious database should be cleared first
sadd key members #添加元素 smembers key #查看所有值 sismember key 元素 #查看某个元素是否在集合中 scard key #查看集合有多少元素 srandmember key count #随机获取key中count个值，不写count默认1个 spop key #随机移除元素
Adding duplicates will be unsuccessful, return false
smove key1 key2 元素 #将一个指定的值移动到另一个Set集合中 sinter key1 key2 #求key1和key2的交集 sunion key1 key2 #求两个的并集
This intersection is like in WeChat, it will show how many friends have followed a certain official account, and then make an intersection between the friend’s official account and yourself. The bloggers who follow in Weibo are also
Map collection, key-map , That is, the key corresponds to a map, and the map has its own key-value pair, key-value, where the value becomes the map.
hset key field value #key-map，map即field和value hget key field #取值 hmset key field1 value1 field2 value2... #存多个值 hmget field1 field2 #取多个值
hdel key field #删除指定的key对应的map hgetall key #获取所有key中所有的field-value
hlen key #判断key的长度（多少个map） hkeys key #获取key对应map中的所有字段 hvals key #获取key对应map中的所有值
hincrby key field 自增值
We can actually set our own user object, user:1 represents the user with id 1, which is often used for user information storage or object storage
ZSet is an ordered set with an additional score count bit for sorting ,
flushdbClear the previous database
zadd key score1 value1 score2 value2 #增加了一个score，会根据score大小排序
The biggest role of zset is sorting, then let’s sort it out and sort the salaries of employees.
zrangebyscore salary (2000 3000 #薪水在(2000,3000]的员工 zrangebyscore salary -inf +inf withscores limit 0 1 #最小，limit表示从下标为0的位置查一个 zrevrangebyscore salary +inf -inf withscores limit 0 1 #最大
The following is to find one from the subscript 1 and subscript 2 positions. End of