Preface

Redis Is an open source use ANSI C Language writing 、 Support network 、 Log type that can be memory based or persistent 、Key-Value database , And provide multilingual API. from 2010 year 3 month 15 The date of ,Reids Development work by VMware host .Redis Can run on most POSIX(Linux,*BSD,OS X and Solaris etc. ) On the system .

And ordinary Key-Value Different structure ,Redis Of Key Support flexible data structures , except strings, also hashes、lists、sets and sorted sets Isostructure . It's these flexible data structures , Enriched Redis Application scenarios of , More flexible storage to meet business needs .

Redis The data of is saved in memory , And the underlying implementation is written by myself epoll enent loop part , And not open source libevent And so on , So reading and writing are very efficient . In order to achieve Redis The persistence of ,Redis Support periodic refresh ( This can be achieved by configuration ) Or write a log to save data to disk .

 

1、Redis Core concept of

「Redis What is it? :」

  • MySql/Oracle: It's a relational database ( There are tables in relational databases and the relationship between tables

  • Redis: It's a no sql The database of ---> Or database ( Non relational databases )

  • Non relational databases : In short, non relational databases don't have tables and relationships between them like relational databases , There are only key value pairs in non relational databases

  • In a non relational database, in fact , Only key value pairs are stored , It's like Map This collection is the same , There are only key value pairs

  • Redis In fact, it's just a file storage system based on key value pairs

「 doubt :」

  • Do we have a grasp of Redis after , You don't use relational databases (mysql/oracle) Well ?

 No, it isn't   In general, when developing   We usually   Is to use   Mix relational database with non relational database    Each in his element   Has achieved the user's good experience effect
Not all of them Redis Not all of them mysql
Common non relational databases :mogodb

2、Redis Can do ?

「 Main uses :」

  • Single sign on above Baidu (SSO)

  • Comments on the mall

  • Points above the mall

  • The shopping cart

  • Cache on the mall ( It mainly refers to : Data common to all users )

  • The calculation of the latest and hottest goods

  • The implementation of message queue

  • ...

3、Redis Characteristics

「 User management command :」

  • Memory based ( Information is in memory The speed of the visit is very fast )

  • The data structure is simple (Key-Value)

  • Support data persistence ( It can synchronize the data in the memory to the hard disk )

4、Redis Installation

「 The installation process :」

  • Download address :http://redis.io/download

 Installation steps :
    1  Installation is required first gcc, Download it okay redis-3.0.0-rc2.tar.gz  Put it in linux /usr/local Under the folder
       yum install gcc
    2  unpack  tar -zxvf redis-3.0.0-rc2.tar.gz
    3  Enter into redis-3.0.0 Under the table of contents , Compile  make
    4  Enter into src Install under  make install   verification (ll see src Directory below , Yes redis-server 、redis-cil that will do )
    5  Create two folders to store redis Commands and configuration files
     mkdir -p /usr/local/redis/etc
     mkdir -p /usr/local/redis/bin
    6  hold redis-3.0.0 Under the redis.conf  Move to /usr/local/redis/etc Next ,
 
      cp redis.conf /usr/local/redis/etc/
    7  hold redis-3.0.0/src Inside mkreleasehdr.sh、redis-benchmark、redis-check-aof、redis-check-dump、redis-cli、redis-server 
      File move to bin Next , command :
     mv mkreleasehdr.sh redis-benchmark redis-check-aof redis-check-dump redis-cli redis-server /usr/local/redis/bin
    8  At startup and specify the configuration file :./redis-server /usr/local/redis/etc/redis.conf( Pay attention to using background startup , So modify redis.conf Inside       daemonize  Change it to yes)
    9  Verify successful startup :
ps -ef | grep redis  Check to see if there is redis service   perhaps   Check the port :netstat -tunpl | grep 6379
      Get into redis client  ./redis-cli  Exit client quit
/exit sign out redis service : 
    (1)pkill redis-server 、
    (2)kill  Process number 、
                            
    (3)/usr/local/redis/bin/redis-cli shutdown

5、Redis And the usage scenarios of data types in

「 Data types and usage scenarios :」

 String
       What is the application scenario ? Ordinary data cache is usually put in this    It has a wide range of application scenarios     Because it's just a string of key value pairs
     List( It can be repeated )
       Application scenarios : This is generally used in : Blog attention 、 Blog comments 、 Blog points
     Hash
       Application scenarios :SSO Single sign on
     Set( Disorder but not repetition )
       Application scenarios : This is usually used with List Same but not repeated    
    SetSort
       Application scenarios : The latest and hottest product ( Orderly )

6、Redis Common commands in ( Data type related )

「 Common commands :」

 set key value:     Set the value
  
    get key            Get the value of a certain type
    keys *             Look at all the keys
    
    del key1,key2..     Delete one or more data
    rename  The original key    Now? key Name      Name the key again
    keys *   List all the keys in the current database
    // stay Redis Default in 16 A database    The subscript of the database is 0-15    By default, the data will be stored in  0 In the database No
    select index     Select a database
    keys *          Support fuzzy query
    exists key       Determine whether there is a specific... In the current data database key( Be careful : Not all databases    It's the database that is currently operating )
    type key        The type of judgment value
    expire key  Time ( Unit second )    Set up key The expiration time of
    ttl key      see key The expiration time of
    persist  key    ( Put a certain key Set to permanent )   
    set key value     Store the data
    mset key value key value  key value     Set multiple key value pairs at once    Be careful : There is no sign in the middle
    mget a1 a2 a3 a4      Get multiple values at once
    append key1 value     In a certain key Add a value to the corresponding value
    getset key value      First get key Corresponding value    And then the following values will be   Assign a value to key
    mgetset key value key value   ....     Set values for multiple keys at the same time
    incr key     Self increasing 1
    incrby key step     Each time you add... To the original value   step
    decr key     Self reduction 1
    decrby key step     Each time, decrease the original value  step
  Hash Methods of data type
    Hset field key value   ----> Set the relevant values                       HSet user userToken userInfo
    Hget field key value   ----> Get the value of the setting
    hlen field             ----> What you get is the current hash The total length inside
    hmset field key value ...  ---> Set multiple key value pairs to one name at a time
    hsetnx field key value...  ---> Create this value and user when it doesn't exist
    hkeys *                ----> Look at all the keys
    hincrby field key      ----> Self increasing
    hexists field          -----> See if it exists
  List The value corresponding to the data type
    lpush key value  -----> Add values to it
    lset key index value ---> Modify the value of a location
    lpop key         -----> Bomb stack ( Get this value )
    lrem key count value ----> Delete list Values in the set
    
  Set aggregate
    sadd key value...   ----> towards set Add value to collection
    spop key            ----> obtain set Sets the values added to the collection
    smove key           ----> Delete key
    
  SortSet 
     zadd key value score ----> It means adding elements to key in   score It means the position of sorting
     zrange value  Range ( Start - end ) ---> It means to get data in a certain range
     zrem value : Delete a value 

7、Redis Data persistence problem in

「 Persistence mode :」

  • There are two ways to persist rdb aof

  • Persistence : In short, it is the process of writing memory and data to the hard disk , It's called data persistence

  • If it's memory data, in case of power failure , Data can be lost , So our memory data needs to be persistent

「rdb Pattern :」

  rbd Pattern ( Development usually doesn't need ):  It is based on our time slice to determine when the data and the hard disk are synchronized    In other words, it is assumed that the data will be persisted under certain conditions ( Certain conditions need to be met )、rdb When the mode is used, it will first write the memory data to the zero time file  、 When the data in this memory is written   It will delete the original rdb file , Re write the contents of the zero hour file to rdb In file
    1>: Only when conditions are established can we write ( Conditions :)
    2>: Write the zero file first ----> Delete rdb file -----> write in rdb file
        When you write zero to all files in memory    Relatively speaking, it needs to be operated more frequently IO
    rdb Mode is suitable for backup
   # It means that 900 There's one in seconds key If it changes, you need to synchronize with the hard disk
   save 900 1
   # stay 300 In seconds   If there is 10 individual key If it changes, you need to synchronize with the hard disk
   save 300 10
   # stay 60 In seconds, if there is 10000 individual key If it changes, you need to synchronize with the hard disk
   save 60 10000

「aof Pattern :」

  aof Pattern : This mode is equivalent to appending the original log 、 In fact, it is   It's just synchronization   Changed content    Unchanged content does not need to be synchronized
       He doesn't do it frequently IO
       To use aof Pattern :
      appendonly yes
      # As long as there is one key If it changes, it will synchronize with the background immediately    This mode will not lose data, but    The efficiency is not high    Generally not recommended
      # appendfsync always
      #  This means that it synchronizes with the hard disk every second
      appendfsync everysec
      #  This has to do with memory buffers   Buffer full auto sync    If it's not full, then we have to wait
      # appendfsync no

8、Redis The master-slave replication problem of ( Configure slave )

「 Master slave copy :」

  Suppose now I have a strategy : This strategy is   Be able to access Redis Server requests fall into two categories ( read 、 Write )
 
    Then put the read on a part of the server 、 Write this operation to another part of the server 、 So you can 3W All requests from the server are completed simultaneously
   
    Separate read and write on the server   Also known as read-write separation, the master-slave replication of database actually completes the final function of read-write separation
    Master slave copy : Actually, it means    The master server to write , Read from the server 、 All requests go through the master server
    Master slave replication configuration implementation 

「 The steps of master-slave replication :」

 clone After the server changes slave Of IP Address
     Modify the configuration file ( From the server's configuration file )  
 vim /usr/local/redis/etc/redis.conf 
     First step :slaveof  The host address (eg:119.23.220.148)
 
 bind 0.0.0.0
     The first step is :
     
        #slaveof <masterip> <masterport>
        # The second place to change
        slaveof 112.74.49.17 6379
     The second step :masterauth<master-password>( There is no need to set )
 
 cd /usr/local/redis/bin/
 
 ./redis-cli
     Use info  see role The role can know the master service or the slave service 

9、Redis Sentry mode

「 Sentinel mode :」

  • A single point of the problem : In short, a server is down , All servers are out of service

  • The sentinel model was created to solve the single point problem

  sentry : On guard
    Sentinel mode is actually a program 、 This program is actually used to detect the status of the main server , Once the primary server hangs up 、 Then the server will vote , According to a pre designed election strategy , Finally, a new master server is elected 

「 The realization of sentinel mode :」

   The realization of sentinel mode :( Sentinel is a separate program and redis The operation itself is not related )
    Start the sentinel program on any machine ( From the server )
   1>:quit  shutdown  sign out redis
   2>:copy sentinel.xml To etc Under this document
   3>: modify  sentinel.xml This file   
      dir   -> /usr/local/redis/etc( This is to tell you the path )
      sentinel monitor mymaster ip  port   The number of votes
      sentinel down-after-milliseconds mymaster 5000   How long to check whether the master node is alive or not
    Activate the sentry    You have to keep up with  sentinel This configuration file
   ...server/  ...sentinel.xml --sentinel &

10、Redis Cluster pattern of

「 Cluster building process :」

  1>: You can find 6 Machines to install
  2>: You can find a machine to turn on 6 Ports to install
First of all to redis.conf  Copy it to our etc Next
 cp /usr/local/redis-4.0.6/redis.conf /usr/local/redis/etc/
The first step :
    mkdir -p /usr/local/redis-cluster   // Create folder
The second step
     mkdir 500*     Create it in the folder you just created 6 Server   Configuration file folder
 
The third step
      Original Redis.cnf file copy To our 500* Go to of
Step four
      Modify the configuration
 
     daemonize yes
     port 500*
     bind 192.168.108.135  Change to  0.0.0.0
     dir "/usr/local/redis-cluster/500*/"  It's better to put on ""
     cluster-enabled yes  This needs to open the comment
     cluster-config-file nodes-500*.conf  This needs to open the comment
     cluster-node-timeout 5000  This also needs to open the comments
     appendonly yes
  Step five
    install ruby Related tools of
   yum install ruby
   yum install rubygems
   gem install redis  ( If the wrong version is low, it will be executed   install rvm To the first 9 step ....)
    install rvm
    gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
    \curl -sSL https://get.rvm.io | bash -s stable
     Then enter cd /usr/local/ See if there are more than one in the directory rvm
 
     Then enter  /usr/local/rvm/archives
    Then decompress the compressed file   tar-zxvf rvm-1.29.7.tgz
   3.source /usr/local/rvm/archives/rvm-1.29.7/scripts/rvm  Add a soft connection   amount to windows Create a shortcut , amount to windows Add an environment variable , Found this order
    4.  see rvm Known in the library ruby edition
    rvm list known
    5.  To install a ruby edition
    rvm install 2.3.3
    6.  Use one ruby edition
    rvm use 2.3.3
    7.  Set the default version
    rvm remove 2.0.0
    8.  Uninstall a known version
    ruby --version
    9.  Install again redis That's all right.
    gem install redis   
  
     Turn on every server
  Go to alicloud server to set the port , And the server restarts
     ./redis-server /usr/local/redis-cluster/700*/redis.conf
      Create this cluster
  Get into cd /usr/local/redis-4.0.6/src/ In this directory
  ./redis-trib.rb create --replicas 1 120.78.191.34:7001 120.78.191.34:7002 120.78.191.34:7003 120.78.191.34:7004 120.78.191.34:7005 120.78.191.34:7006
redis-cli --cluster create 106.54.13.167:5001 106.54.13.167:5002 106.54.13.167:5003 106.54.13.167:5004 106.54.13.167:5005 106.54.13.167:5006 --cluster-replicas 1
     Log in to the client to verify
  ./redis-cli -c -h 192.168.108.137 -p 5001
 Jedis Single machine access / Access under connection pool / Access cluster
   Redis Database access depends on Jedis

Conclusion

This article is about Redis This is the end of the introduction , There will be more about Redis More articles in series , Thank you for your support !

Point a praise , Prove that you still love me