preface

Redis is an open source, network-enabled, memory-based and persistent logging, key-value database written in ANSI C, and provides multiple language apis. As of March 15, 2010, the development of Reids was hosted by VMware. Redis runs on most POSIX systems (Linux, *BSD, OS X, Solaris, etc.).

Different from the ordinary key-value structure, the Key of Redis supports flexible data structures, including strings, hashes, Lists, sets and sorted sets. It is these flexible data structures that enrich the application scenarios of Redis and can meet more flexible storage requirements of businesses.

The data of Redis is stored in memory, and in the underlying implementation, the epoll Enent loop part is written by Redis itself, instead of the open source libevent and other general frameworks, so the reading and writing efficiency is very high. For Redis persistence, Redis supports periodic refreshes (which can be configured) or logging to save data to disk.

Public account: “Asanha’s IT Hut”

1. Core concepts of Redis

“What is Redis:”

  • MySql/Oracle: is a relational database (a relational database contains tables and relationships between tables

  • Redis: a no SQL database or a database (non-relational database)

  • Non-relational database: in simple terms, the non-relational database does not exist tables and associated relationships between tables as the relational database, the non-relational database only exists key-value pairs

  • In a non-relational database, there is really only key-value pair storage, just like in a collection like Map, there are only key-value pairs

  • Redis is essentially a file storage system based on key-value pairs

Question:

  • Will we not use relational databases (mysql/ Oracle) once we master Redis?

    Not generally in the development of our general situation is the use of relational database and non-relational database mix has achieved a good user experience is not all with Redis is not all with mysql common non-relational database: MogoDB

2. What can Redis do?

“Main uses:”

  • Single Sign-on (SSO) on Baidu

  • Comments on the mall

  • Points on the mall

  • The shopping cart

  • Store cache (basically: data common to all users)

  • The latest hot commodity calculation

  • Implementation of message queues

  • .

3. Characteristics of Redis

User Management Commands:

  • Memory-based (information is accessed particularly fast in memory)

  • Simple data structure (key-value)

  • Data persistence support (ability to synchronize data in memory to hard disk)

4. Installation of Redis

Installation Process:

  • IO/Download

    Installation steps: 1. Install GCC Redis-3.0.0-rc2.tar. gz /usr/local/yum install GCC 2 decompress tar -zxvf redis-3.0.0-rc2.tar.gz 3 Make 4 Run the following command to verify the installation: make install 5 Create two folders to save the redis command and configuration file mkdir -p /usr/local/redis/etc mkdir -p /usr/local/redis/bin 6 /usr/local/redis/etc; /usr/local/redis/etc cp redis.conf /usr/local/redis/etc/ 7 Mkreleasehdr. sh, redis-benchmark, redis-check-aof, redis-check-dump, redis-cli, redis-server, mkreleasehdr.sh, redis-benchmark, redis-check-aof, redis-cli, redis-server, redis-3.0.0/ SRC, mkreleasehdr.sh, redis-benchmark, redis-check-aof, redis-check-dump, redis-cli, redis-server mv mkreleasehdr.sh redis-benchmark redis-check-aof redis-check-dump redis-cli redis-server /usr/local/redis/bin 8 Startup and specify the configuration file: / redis server/usr/local/redis/etc/redis. Conf (be careful to use background, so modify the redis. Conf daemonize instead yes) in 9 test whether start success: Ps – ef | grep redis see if any redis service or view port: netstat tunpl | grep 6379 into redis client/redis – cli to exit the client the quit/exit exit redis service: (1) pkill redis server, (2) the kill process, (3)/usr/local/redis/bin/redis – cli shutdown

5. Data types in Redis and usage scenarios of data types

“Data Types and Usage Scenarios:”

What is the String application scenario? List(can be repeated) Application scenario: This is commonly used for: blog followers, blog comments, blog integral Hash Application scenario :SSO SSO Set(unordered but not repeated) Application scenario: This is usually used in SetSort applications like List but not repeated: the latest and hottest items (ordered)Copy the code

6, Redis common commands (data type dependent)

Common Commands:

Keys * View all keys del key1,key2.. Delete one or more data rename old key now rename key * Rename key * list all the keys in the current database // Redis has 16 databases by default. The subscripts of databases are 0 to 15 Select index select a database key * Supports fuzzy query exists key determines whether a particular key exists in the current data database (note: not all databases but the current operation database) type key determines the type expire of the value TTL Key Query the expiration time of a key. Persist key (set a key to be valid permanently) Set Key Value Stores data. Mset Key Value Key value Key Mget A1 a2 A3 A4 Obtains multiple values at a time appEnd key1 value Appends the value corresponding to a key getSet Key Value Obtains the value corresponding to the key Then assign the following value to key mgetSet key Value Key value.... Incr Key increment by 1 Incrby key step Increment by 1 decr Key decrement by 1 Decrby key step Decrement step Hset method of the Hash data type step from the original value Field key value ----> Set the related value HSet user userToken userInfo Hget field key value ----> Get the set value hlen field ----> obtain the total length of the current hash hmset field key value... Hsetnx field key value hsetNx field key value --> create this value and user hkeys * ----> view all keys hincrby field key ----> add hexists field -----> check whether there is a lpush key corresponding to the List data type Value -----> add value lset key index value --> change the value of a location lPOP key -----> pop stack (obtain this value) lrem key count value ----> delete the value of the list Set Set sadd key value... ----> add value spop key ----> get value smove key ----> delete key SortSet zadd key value score ---- Zrem value: Delete a value. Zrem value: delete a valueCopy the code

7. Data persistence in Redis

“Persistent mode:”

  • There are two types of persistence, RDB aOF

  • Persistence: Simply put, it is the process of writing memory and data to the hard disk. It is called persistence of data

  • If the data is in memory, the data will be lost in the case of power failure, so our in-memory data needs to be persistent

“RDB mode:”

RBD mode (generally not used in development): When was judged according to our time slice to synchronize the data and the hard drive That is assuming that under certain conditions will persist data (need to meet certain conditions) and RDB mode when using the first memory data written to a temporary file, when the memory data write complete can delete the original RDB file, 2>: Write to a zero time file first ----> Delete the RDB file -----> Write to an RDB file because writing all data in memory to a zero time file requires more frequent operations. IO RDB mode is suitable for backup 1. If 10 keys have changed in 300 seconds, save 300 10 Save 60 10000 if 10000 keys are changed in 60 secondsCopy the code

“Aof mode:”

Aof mode: this mode is equivalent to the original log appending, in effect, just synchronize the changed content, unchanged content does not need to synchronize it does not frequently IO to use aOF mode: # appendfSync always # appendfsync everysec: sync with the hard disk every second # appendfsync no # appendfsync no # appendfsync noCopy the code

8. Redis master/slave replication problem (configuring slave server)

Primary/secondary Replication:

Now suppose I have a strategy: The strategy is to divide the requests to the Redis server into two types (read and write) and then put the read on one part of the server and the write on another part of the server, so that all the requests to the server can be completed in 3W and the read and write on the server can be separated Also known as read/write separation, the primary/secondary replication of a database actually performs the final function of read/write separation. In fact, the primary server implements the write, the secondary server implements the read, and all requests pass through the primary server to complete the configuration of the master/secondary replicationCopy the code

“Steps for master/slave replication:”

Clone server after modifying the IP address of the slave Modify the configuration file (from the server's configuration files) vim/usr/local/redis/etc/redis. The first step in the conf: slaveof host address (eg: 119.23.220.148) bind Step 1:0.0.0.0 #slaveof <masterip> <masterport> Masterauth <master-password> CD /usr/local/redis/bin/. /redis-cli View roles Using info You can know the master or slave serviceCopy the code

9. Sentinel mode of Redis

“Sentinel mode:”

  • Single point of problem: Simply put, one server is down and all servers are down

  • The Sentinel model was invented to solve the single point problem

    Sentinel: Sentinel mode is actually a program that detects the state of the master server. Once the master server is down, the slave server will vote for a new master server according to a pre-designed election strategy

“Implementation of sentinel pattern:”

Start sentinel on any machine (from the server) 1>:quit shutdown redis 2>:copy sentinel. XML to etc -- /usr/local/redis/etc -- /usr/local/redis/etc Down-after-milliseconds myMaster 5000 how long does it take to check whether the primary node is alive or not? server/ ... sentinel.xml --sentinel &Copy the code

10. Redis cluster mode

“Cluster Building Process:”

2>: you can install redis.conf on a machine with 6 ports. Copy redis.conf to /etc/cp /usr/local/redis-4.0.6/redis.conf /usr/local/redis/etc/ Mkdir -p /usr/local/redis-cluster // create a folder step 2 mkdir 500* Create a folder for the configuration files of the six servers in the newly created folder step 3 Daemonize yes port 500* bind 192.168.108.135 to 0.0.0.0 dir "/usr/local/redis-cluster/500*/" "cluster-enabled yes "" cluster-config-file nodes-500*.conf "" cluster-enabled yes Cluster-node-timeout 5000 appendonly yes ruby yum install Ruby yum install rubygems gem install Redis (Install RVM to step 9....) Install RVM GPG -- keyserver hkp://keys.gnupg.net -- recv - keys 409 b6b1796c275462a1703113804bb82d39dc0e3 \ curl - sSL https://get.rvm.io | bash - s stable and then into CD/usr/local/directory to see if multiple RVM then enter/usr/local/RVM/archives compressed file decompression tar ZXVF - again RVM - 1.29.7. TGZ 3. The source/usr/local/RVM/archives/RVM - 1.29.7 / scripts/RVM add a soft connection The equivalent of Windows to create a shortcut, Equivalent to Windows add an environment variable, find the command 4. RVM list known 5. RVM install 2.3.3 6. RVM use 2.3.3 7. Set the default RVM to remove 2.0.0 8. Gem install redis start each server to go to Ali cloud server to set the port, Redis-server /usr/local/redis-cluster/700*/redis.conf create the cluster and go to CD /usr/local/redis-4.0.6/src/ ./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.35:7005 120.78.191.35:7006redis -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 Logs in to the client for authentication./redis-cli -c -h 192.168.108.137 -p 5001 Jedis Performs single-node access/connection pool access/access the Redis database in the cluster depends on JedisCopy the code

conclusion

This is the end of this introduction to Redis, and there will be more articles about Redis in the future. Thank you for your support!

“Like” to prove you still love me