当前位置:网站首页>Redis learning
Redis learning
2022-07-27 22:30:00 【XUPT-BDAL-LAB-ML&OP】
1. What is? nosql
NoSQL(NoSQL = Not Only SQL ), Means against SQL motion , Is a new database revolutionary movement ,2000 It was proposed years ago , To 2009 The annual trend is rising . It refers to the use of non relational data storage , Relative to the overwhelming use of relational databases , This concept is undoubtedly an injection of new thinking .
With the Internet web2.0 The rise of websites , Traditional relational databases are coping web2.0 Website , Especially large scale and high concurrency SNS Type of web2.0 Pure dynamic website has appeared to be powerless , A lot of insurmountable problems were exposed , The non-relational database has developed rapidly due to its own characteristics .NoSQL The emergence of database is to solve the challenge of large data sets and multiple data types , Especially big data application problem .
2. NoSQL Characteristics of ?
NoSQL yes key-value stored , Unlike traditional relational databases , Not necessarily following some basic requirements of traditional databases , For example, follow SQL standard 、ACID attribute 、 Table structure and so on .
This kind of database mainly has the following characteristics :
- Non relational 、 Distributed 、 Open source 、 Horizontally scalable processing of huge amounts of data
- Broke the performance bottleneck
- Read and write data with high concurrency
- Efficient storage and access of massive data, high scalability and high availability of data
3. What is? Redis?
Redis It's an open source , advanced key-value Storage . It is often referred to as a data structure server , Because keys can contain string( character string )、hash( Hash )、list( Linked list )、set( aggregate ) and zset(sorted-set– Ordered set ). These data types support push/pop、add/remove And take intersection, union and difference sets and more abundant operations .
Redis and Memcached similar , It supports storage value There are more types , And memcached equally , To ensure efficiency , The data is cached in memory , The difference is that Redis Periodically, updated data is written to disk or changes are written to an appended log file , And on this basis to achieve master-slave( Master-slave ) Sync .

4.Redis Installation and deployment
Redis The official website of :http://redis.io
Download installation package :
# wget http://download.redis.io/releases/redis-2.8.6.tar.gz
Compilation and installation :
# tar –zxvf redis-2.8.6.tar.gz # cd redis-2.8.6
# make
# make PREFIX=/usr/local/redis install
Specify the installation location , If the installation location is not specified PREFIX=/usr/local/redis, be make install Will be able to redis The installation to /usr/local/bin/ Under the table of contents
# mkdir /usr/local/redis/etc
# cp ./redis.conf /usr/local/redis/etc/
Copy Redis Configuration file to /usr/local/redis/etc/ Next , Easy to manage .
Modify the configuration file :
# vi /usr/local/redis/etc/redis.conf
daemonize no It is amended as follows yes # Background start
Start the service :
# /usr/local/redis/bin/redis-server The configuration file
Configuration file location must be specified , Otherwise, a warning will be prompted
Client connection :
/usr/local/redis/bin/redis-cli
-h IP: Connect the specified redis The server
-p 6379: Appoint redis The port of the server
-a password : Log in with password
-n Database number : Specify which database to connect to
--raw: redis Support to store Chinese
stop it Redis:
# /usr/local/redis/bin/redis-cli shutdown
or
# pkill -9 redis
5.Redis Common commands
1) string Type and operation
string Is the simplest type , One key Corresponding to one value,string Type is binary safe .redis Of string Can contain any data .
1.set: Set up key The corresponding value is string type
for example : Let's add a name=atguigu The key value of corresponds to
redis127.0.0.1:6379>set name atguigu
2.setnx: Set up key The corresponding value is string type , If key Already exist , return 0,nx yes not exist It means
3.get: obtain key Corresponding string value , If key There is no return nil
4.mset & mget Set and get multiple key value pairs at the same time
5.incrby: Yes key The value of plus ( Specify the value ) operation , And return the new value
6.del: Delete a created key
2)hash Type and operation
Redis hash It's a string Type of field( Field ) and value Mapping table , Its addition 、 Delete operations are 0(1) Average ;hash Ideal for storing objects , Instead of saving each field of an object as a single string type , Store an object in hash Type takes up less memory , And it can be more convenient to access the entire object .
1.hset: Set up hash field For the specified value , If key non-existent , First create . for example : by num1 Create a table called name Field (key), The key value is liuchuan redis127.0.0.1:6379>hset num1 name liuchuan
2.hget、hmset、hmget The meaning is similar to that of
3.hdel: Delete a key value pair in the formulation table
4.hgetall: List all key value pairs in the table
3)list Type and operation
list Is a linked list structure , The main functions are push、pop、 Get all the values in a range, and so on , In operation key The name of the list .Redis Of list Type is actually a sub element string Double linked list of type . We can go through push、pop Operation adds or deletes elements from the head or tail of the linked list .
1.lpush: stay key Corresponding list Add string elements to the header of .redis127.0.0.1:6379>lpush zhangsan zhangsan redis127.0.0.1:6379>lpush zhangsan 18
2.lrange: Get the elements of the specified range from the specified linked list redis127.0.0.1:6379>lrange zhangsan 0 -1
0 -1: This range represents all elements , It means from beginning to end
3.lpush、rpush、lpop、rpop、lrange See the figure for details 
4)Set Type and operation
set Is a collection , He is string Unordered collection of type .Set It's through hash table Realized , Pair set 、 intersection 、 Difference set . Through these operations, we can realize friend recommendation and blog Of tag function . Set cannot have duplicate values .

1.sadd: Add one or more elements to the collection redis127.0.0.1:6379>sadd mset 1 2 3 4
2.smembers: Get all the elements in the collection redis127.0.0.1:6379> smembers mset
3.srem: Deletes the specified element or elements from the collection
4.spop: Randomly delete an element from the collection , And back to
5.scard: Get the number of elements in the collection
6.sdiff: Back to the assembly 1 And assemble 2 The difference between the set . To gather 1 Mainly
redis127.0.0.1:6379>sdiff mset1 mset2
7.sinter: Get the intersection of two sets
8.sunion: Get the union of the specified set
5)zset Type and operation
zset yes set An updated version of , It's in set Add a sequence attribute based on the , This attribute can be specified when adding modification elements , After each assignment ,zset Automatically reorder to the new value . It can be understood as having two columns mysql surface , A list of stored value, A sequence of storage . In operation key Understood as a zset Name .

- zadd: Add elements to a specified ordered set , Each element will have a corresponding score . You can specify multiple points
/ Member groups . If a specified member is already in the corresponding ordered set , Then the score will be updated to the latest , And the member will be relocated to the right place , To make sure the assembly is in order . The value of the fraction must be a string representing the number .redis127.0.0.1:6379>zadd zset 2 zhangsan 1 lisi 1 wangwu - zrange: Return to the ordered set , Specify the members in the interval . Among them, the members follow score( fraction ) Rank values from small to large . Have the same score The members of values are arranged in dictionary order .
redis127.0.0.1:6379>zrange zset 0 -1 withscores
notes : withscores While returning the elements in the collection , Returns its score (score) - zrem: Delete the specified value in the ordered set redis127.0.0.1:6379>zrem zset zhangsan
- zcard: Returns the number of elements in an ordered set
6) Other relevant orders
- keys: Find the specified key by key name . Support for wildcards (* ? etc. ) redis127.0.0.1:6379>keys h*llo
- exists: Confirm whether a key exists (1 Indicates presence )
- del: Delete a key ( Universal )
- expire: Set a key ( Already exists ) The expiration time of , If the key has expired , Will be automatically deleted
- ttl: In seconds , Returns the remaining valid time of the specified key
When key When there is no , return -2 .
When key When the remaining lifetime exists but is not set , return -1 . otherwise , In seconds , return key The remaining lifetime of . - select: Select a database , The default database to connect to is 0, Can support a total of 16 A database . In the configuration file , adopt
databases 16 Keyword definition . - move: Move the key of the current database to the specified database
- type: Return the type of key
- dbsize: Returns the number of keys in the current library ( All types )
- save: Save all the data . Rarely used directly in a production environment SAVE command , Because it blocks all client requests , have access to BGSAVE Command instead of . If in BGSAVE When an error occurs in the sub process of saving data of the command , use SAVE The command to save the latest data is the last resort .
- info: Get the details of the server
- config get: obtain redis Parameters in the server configuration file . Support for wildcards
- flushdb: Delete all data in the current database
- flushall: Delete all data in all databases
6. Redis Advanced applications
1) Password protection
1、 Modify the configuration file
# vi /usr/local/redis/etc/redis.conf requirepass 123456
2、 restart redis # pkill redis
# …/bin/redis-server …/etc/redis.conf
3、 Client login
# …/bin/redis-cli -a 123456
Or in interactive mode 【auth password 】 command
2) Master slave synchronization
Redis Master slave replication process :
- Slave And master Establishing a connection , send out sync Synchronization command
- Master A background process will be started , Save the database snapshot to a file , meanwhile master The main process will start collecting new write commands and caching .
- After the background is saved , Send this file to slave
- Slave Save this file to your hard disk
1. The master server can set the password for itself (iptables&SELinux close )
2. Modify the configuration file from the server , Used to connect to the main server
The old version :
from :
slaveof <masterip> <msterport> # Of the main server IP And port
masterauth <masterpass> # The password for the primary server ( The master server should set the password )
The new version redis 5.* above : Lord :
find bind 127.0.0.1 Comment out , Or change it to native IP Address ( restart ) from :
replicaof <masterip> <msterport> # Of the main server IP And port
masterauth <masterpass> # The password for the primary server ( The master server should set the password )
3. Restart the slave server , Then test ( It can be done by info Command to get the current server identity type )
Reading the configuration file, at line 88 >>> 'protected-mode no' Bad direc
http://www.gosanye.com/post/9859.html
3) Data persistence
RDB
snapshotting( snapshot )– Default mode
RDB Persistence allows you to store snapshots of your data at specified intervals . It's the default way to persist . This method is to write the data in memory to the binary file in the form of snapshot , The default filename is dump.rdb. This persistence is called snapshot snapshotting( snapshot ).
After that 900 Seconds and there are 1 individual key It has changed It will trigger save action # After that 300 Seconds and there are 10 individual key It has changed It will trigger save action # After that 60 Seconds and at least 10000 individual key It has changed It will also trigger save action
Conclusion : stay redis.conf In file dir ./ Defines the storage location of database files , The default is the current directory . So every time you restart redis
The location of the service is different , Will generate new dump.rdb file ; It is recommended to modify the location where the snapshot file is saved when the server is set up .
RDB Starting mode —— save Instruction related configuration
dbfilename dump.rdb
explain : Set the local database file name , The default value is dump.rdb
Experience : Usually set to dump- Port number .rdb
dir
explain : Set up storage .rdb
Experience : Usually set to save
rdbcompression yes
explain : Store settings locally
Experience : Usually, it defaults to open
rdbchecksum yes
, The default is yes, use LZF Compress
Set to no, Can save CPU The elapsed time , But it makes the stored files bigger ( huge )
explain : Set whether to RDB File format verification , The verification process is carried out in the process of writing and reading files
Experience : It is usually on by default , If set to no, It can save the reading and writing process about 10% Time consuming , However, there is a certain risk of data corruption
AOF
append-only file( abbreviation aof)
Use AOF Will let you Redis More durable : You can use different persistence strategies : Back up every time you write 、 Backups per second 、 No backup . Use the default backup per second policy ,Redis The performance is still very good ( The backup is processed by the background thread , The main thread will try its best to handle client requests ), In case of failure , The most you lose 1 Second data .
open redis.conf Profile on AOF Persistence
appendonly no
Default not to use AOF Persistence (450 That's ok ) take no Change to yes.# appendfsync always
There are write operations , Write to disk immediately . The slowest efficiency , But the safest
appendfsync everysec
Default , Write to disk once per second .
appendfsync no
Don't make AOF Backup , Give the data to the operating system for processing . The fastest , The least safe
test : restart redis service , Sign in client Add a key value , Quit and ls Command to check whether appendonly.aof.
It can be used cat see .
4) Sentinel mode
sentry (sentinel) It's a distributed system , It's used to do... On each server in the master-slave structure
monitor , When there is a failure, the voting mechanism is used to select a new one master And put all slave Connect to the new master.
The role of a sentry
- monitor
Keep checking master and slave Is it working .master Survival tests 、master And slave Operation detection - notice ( remind )
When there is a problem with the monitored server , To the other ( The sentry room , client ) Sending notice . - Automatic failover
To break off master And with slave Connect , Pick one slave As master, Will others slave Connect to the new master, And inform the client of the new server address
https://blog.csdn.net/qq_44299529/article/details/123256648
mysql And redis combination
link :https://pan.baidu.com/s/14qXfId2sTAUB2LycFk2guQ?pwd=0i0t
Extraction code :0i0t
-- From Baidu network disk super member V4 The share of
边栏推荐
- 只会Excel想做图表可视化,让数据动起来?可以,快来围观啦(附大量模板下载)
- [illustration] shake hands three times and wave hands four times - it's enough to read this article carefully
- Vs2019 release mode debugging: this expression has side effects and will not be evaluated.
- Leetcode 148. sorting linked list
- 饿了么input输入框设置type=‘number‘时,去掉后面的上下按钮
- Interview questions that big companies need to prepare
- Live video source code, uni app to achieve advertising scroll bar
- 华能福建公司与华为数字能源深化战略合作,共建低碳智能县域
- Nine days later, we are together to focus on the new development of audio and video and mystery technology
- Apachespark command execution (cve-2022-33891) vulnerability recurrence
猜你喜欢
![[illustration] shake hands three times and wave hands four times - it's enough to read this article carefully](/img/b1/af520cec44e849e8828a86fc7a2614.png)
[illustration] shake hands three times and wave hands four times - it's enough to read this article carefully
![[Marine Science] climate indices data set](/img/0f/f63b946b80fc2cf1d39a975c318abc.png)
[Marine Science] climate indices data set

Inventory Poka ecological potential project | cross chain characteristics to promote the prosperity of multi track

Reed relay

Seven lines of code crashed station B for three hours

Deepfake's face is hard to distinguish between true and false, and musk Fenke has disguised successfully

Alibaba Senior Software Testing Engineer recommends testers to learn -- Introduction to security testing

Behind every piece of information you collect, you can't live without TA

Huaneng Fujian company and Huawei digital energy deepen strategic cooperation and jointly build a low-carbon smart county

ThreadLocal principle and source code analysis (click in step by step, don't recite, learn ideas)
随机推荐
Chapter 3 business function development (choose to export market activities, Apache POI)
全国职业院校技能竞赛网络安全竞赛数据取证与分析思路分析
视频直播源码,uni-app实现广告滚动条
matlab 绘制三坐标(轴)图
ThreadLocal principle and source code analysis (click in step by step, don't recite, learn ideas)
[stonedb fault diagnosis] MDL lock waiting
The execution process, orphan process and zombie process of fork() function
fork()函数的执行过程、孤儿进程和僵尸进程
Solid state relay
Vocational school Panyun network security competition ----- exploration of hidden information
How to quickly pass the probation period for newly trained intermediate test engineers
云原生微服务第三章之Haproxy+Keepalived
MySQL series - database tables, queries, sorting, and data processing functions
【图解】三次握手,四次挥手 —— 用心看这一篇就够了
Leetcode-199-right view of binary tree
ApacheSpark-命令执行(CVE-2022-33891) 漏洞复现
阿里资深软件测试工程师推荐测试人员必学——安全测试入门介绍
2022 / July daily report
Can uniswap integrate sudoswap to open a new prelude to NFT liquidity?
【StoneDB故障诊断】MDL锁等待