当前位置:网站首页>Redis tutorial
Redis tutorial
2022-07-25 01:45:00 【51CTO】
redis course :
summary
redis It's a kind of nosql database , His data is stored in memory , meanwhile redis Can regularly synchronize memory data to disk , That is, data can be persisted , And he's better than memcached Support more data structures (string,list list [ Queues and stacks ],set[ aggregate ],sorted set[ Ordered set ],hash(hash surface )). Relevant reference documents : http://redisdoc.com/index.html
redis Use scenarios :
- Login session store : Stored in
redis in , And memcached comparison , Data will not be lost . - Ranking version / Counter : For example, some show projects , There are often some top anchor rankings . There are also some techniques for reading articles , Or the number of likes on Sina Weibo .
- As message queue : such as
celery Is the use of redis As a middleman . - The current number of people online : Or the previous show example , It will show how many people are online in the current system .
- Some commonly used data caching : Like our
BBS Forum , Plates don't change often , But every time you visit the home page, you have to start from mysql In order to get , Can be in redis In the cache , You don't have to request the database every time . - The former 200 Article cache or comment cache : General users browse websites , I will only browse the previous articles or comments , Then you can put the front 200 Article and corresponding comments are cached . User access exceeds , Just access the database , And later articles exceed 200 piece , Delete the previous article .
- Friend relationship : Microblogging friends use
redis Realization . - Publish and subscribe : Can be used to make chat software .
redis and memcached Comparison :
memcached | redis | |
type | Pure memory database | Memory disk synchronization database |
data type | In defining value We need to fix the data type | Unwanted |
Virtual memory | I won't support it | Support |
Expiration strategy | Support | Support |
Storage data security | I won't support it | You can synchronize data to dump.db in |
disaster recovery | I won't support it | You can restore the data in the disk to memory |
Distributed | Support | Master slave synchronization |
Subscribe and publish | I won't support it | Support |
redis stay ubuntu Installation and startup in the system
- install :
- uninstall :
- start-up :
redisAfter installation , It will start automatically by default , You can view... With the following command :
If you want to start it manually , You can start with the following command :
- stop it :
Yes redis The operation of
Yes redis There are two ways to do this , The first way is to use redis-cli, The second way is programming language , such as Python、PHP and JAVA etc. .
- Use
redis-cli Yes redis String operation : - start-up
redis:
- Connected to the
redis-server:
- add to :
String value value Related to key. If key Has held other values ,set The order overwrites the old value , Regardless of the type . And the default expiration time is permanent , That is, it will never expire .
- Delete :
- Set expiration time :
You can also set the value when , Specify expiration time together :
- View expiration time :
- View the current
redis All in key:
- The list of operations :
- Add an element to the left of the list :
Will value value Insert into list key The header . If key non-existent , An empty list is created and executed lpush operation . When key When there is but not a list type , An error will be returned .
- Add an element to the right of the list :
Will value value Insert into list key At the end of the watch . If key non-existent , An empty list is created and executed RPUSH operation . When key When there is but not a list type , Return an error .
- View the elements in the list :
Returns a list of key The elements in the specified interval , The interval is offset by start and stop Appoint , If you want the first to the last on the left lrange key 0 -1.
- Remove the elements from the list :
- Remove and return to list
key The head element of :
- Remove and return the last element of the list :
- Remove and return to list
key The intermediate element of :
Will delete key In this list ,count The values are value The elements of .
- Specifies the number of elements to return :
Will return key In this list , The index for index This element of .
- Get the number of elements in the list :
- Delete the specified element :
According to the parameters count Value , Remove the list and parameters value Equal elements .count The values of can be the following :
- count > 0: Search from header to footer , Remove and
value Equal elements , The number of count. - count < 0: Search from the end of the table to the header , Remove and
value Equal elements , The number of count The absolute value of . - count = 0: Remove all and from the table
value Equal value .
-
set Operations on collections :
- Additive elements :
- Check out the elements :
- Remove elements :
- View the number of elements in the collection :
- Get the intersection of multiple sets :
- Get union of multiple sets :
- Get the difference set of multiple sets :
-
hash The hash operation :
- Add a new value :
Hash table key In the domain field The value of the set value.
If key non-existent , A new hash table is created and executed HSET operation . If the domain field It already exists in the hash table , The old value will be overwritten .
- Gets the in the hash
field Corresponding value :
- Delete
field One of the field:
- Get all in a hash
field and value:
- Get all in a hash
field:
- Get all the values in a hash :
- Determine if there is a... In the hash
field:
- Get the total key value pairs in the hash :
- The transaction operations :Redis Transactions can execute more than one command at a time , Transactions have the following characteristics :
- Isolation operation : All commands in the transaction are serialized 、 To execute in order , Will not be disturbed by other orders .
- Atomic manipulation : The commands in the transaction are either all executed , Or none of it .
- Start a transaction :
All future commands , Are executed in this transaction .
- Perform transactions :
Will be in multi and exec Submit together with the operations in .
- Cancel the business :
Will multi All subsequent commands are cancelled .
- Monitor one or more
key:
Watch one ( Or more )key, If before the transaction is executed ( Or these ) key Altered by other orders , Then the business will be interrupted .
- Cancel all
key Surveillance :
- Release / Subscription operation :
- Post a message to a channel :
- Subscribe to messages on a channel :
- Persistence :
redis Two data backup methods are provided , One is RDB, The other is AOF, These two backup strategies are described in detail below :
| | RDB | AOF | | --- | --- | --- | | On off | Turn on : Default on . close : Put all in the configuration file save All notes , It's just shut down . | Turn on : In the configuration file appendonly yes It turns on aof, by no close . | | Synchronization mechanism | You can specify how many commands occur in a certain time to synchronize . such as 1 Within minutes 2 subcommand , Just synchronize once . | Synchronize every second or after every command | | Store content | What's stored is redis The specific value inside | What is stored is the operation command of updating data executed | | The path where the file is stored | according to dir as well as dbfilename To specify the path and specific file name | according to dir as well as appendfilename To specify the specific path and file name | | advantage | (1) Storing data in a file is compressed , File volume ratio aof Small .(2) Because it stores redis Specific value , And it will be compressed , Therefore, the recovery speed is faster than AOF fast .(3) Ideal for backup . | (1)AOF Our strategy is to synchronize every second or every time a write occurs , So even if the server fails , At most, it will only be lost 1 Second data . (2)AOF What's stored is Redis command , And it is directly added to aof Behind file , So every time you back up, just add new data .(3) If AOF The file is quite large , that Redis Will be rewritten , Keep only the smallest set of commands . | | shortcoming | (1)RDB The synchronization mechanism will start when how many write operations occur in how long , Because of the compression mechanism ,RDB When synchronizing, save the whole again Redis Data in , So you usually set it at least 5 The data is saved only once per minute . under these circumstances , Once the server fails , Can cause 5 Minutes of data lost .(2) Save the data in RDB When ,Redis Meeting fork A child process is used to synchronize , When the amount of data is large , It can be very time consuming . | (1)AOF The file is not compressed , So the volume ratio RDB Big . (2)AOF Backup every second or every write operation , Therefore, if the concurrency is large , Efficiency may be a little slow .(3)AOF File because it stores commands , So in disaster recovery Redis It will run again AOF The command , Not as fast as RDB. | | more | http://redisdoc.com/topic/persistence.html#redis | | - Security : In the configuration file , Set up
requirepass password, When the client connects , Need to use password :
Python operation redis
- install
python-redis:
- Create a new file, such as
redis_test.py, Then initialize a redis Instance variables , And in ubuntu Open in virtual machine redis. For example, virtual machine ip The address is 192.168.174.130. The sample code is as follows :
- Operations on strings : operation
redis Method name of , Same as before redis-cli equally , Now let's make a brief introduction to some commonly used , The sample code is as follows ( Undertake the above code ):
- Operations on lists : Same string operation , Name and use of all methods
redis-cli The operation is the same :
- Operations on sets :
- Pair hash (
hash) The operation of :
- Business ( The Conduit ) operation :
redis Support transaction operations , That is, some operations can only be completed uniformly , It's done . Otherwise, the execution fails , use python operation redis It's also very simple , The sample code is as follows :
The above shows python-redis Some common methods of , If you want to know more about other methods , You can refer to python-redis Source code ( View the source code pycharm Shortcut key prompt : Place the mouse cursor on import Redis Of Redis On , Then press ctrl+b You can enter ).
边栏推荐
- Pursue and kill "wallet Assassin" all over the network
- Contemporary fairy quotations
- Create the first hbuilder project
- The cloud ecology conference comes with the "peak"!
- Ad active directory and domain network
- [28. Maximum XOR pair]
- Mongodb security cluster construction
- Latex notes
- Beijing Zhun electric clock, Beidou clock server, GPS network time server, NTP satellite timing system
- Several schemes of traffic exposure in kubernetes cluster
猜你喜欢

How can arm access the Internet through a laptop?

Young people who lost the IPO

Worthington carboxyl transfer carbonic anhydrase application and literature reference
![[C + + primer notes] Chapter 6 functions](/img/9a/b79e7c3013678038420faee329d6b6.jpg)
[C + + primer notes] Chapter 6 functions

Tiktok iqiyi announced cooperation, long and short video handshake and reconciliation?

After burning up 130 billion yuan in ten years, vertical e-commerce will eventually enter the dust of history

Synchronization primitive: lock

Eolink - quickly develop interfaces through document driven

EasyX realizes button effect

Data integration | what are the tools for data integration at home and abroad?
随机推荐
[27. Expression evaluation (infix expression)]
Call camera photo album / upload / scan code in uniapp
Web Security Foundation - file upload
Start to build a three node Eureka cluster
Alibaba cloud released the white paper "upgrade - standardization of data warehouse upgrade delivery"
Target segmentation for 10000 frames of video, less than 1.4GB of video memory, open source code | ECCV 2022
JVM Foundation
Ireport export PDF font bold failure
Hcip - BGP - border gateway protocol
Research and application of scientific data management strategy for high energy synchrotron radiation source
Peripherals: timer, watchdog and RTC
[development tutorial 10] crazy shell · open source Bluetooth smart health watch OTA image production and download technical documents
Several schemes of traffic exposure in kubernetes cluster
Seven text editors that programmers should know are necessary for programming
Boutique solution | Haitai cloud password application service solution to create secure and compliant Cloud Applications
Document the use of anti shake in packaged components and projects
Fabric. JS centered element
Hbuilderx developed by uni app connects to night God simulator
Ad active directory and domain network
Introduction to ORM framework - what is ORM framework?