Introduction to Redis

1.1 introduction of redis

Redis is an open source, net-based, memory-based and persistent logging, key-value database written in ANSI C language. It provides apis in multiple languages. Value can be string, hash, list, set, zset, and other data structures. It can meet many application scenarios. It also provides key expiration, publish and subscribe, transactions, pipelining, and other additional features

Assembly line

The Redis pipeline function allows the client to send multiple command requests to the server at one time and return the results of the multiple command requests to the client in one command reply. Using this function can effectively reduce the number of times the client needs to communicate with the server when executing multiple commands.

Data storage

1, Redis installed on disk;

2. Redis data is stored in memory

Redis is simple to use

For example, the database has a table Order with a primary key orderID

1.2 Redis features

  1. Fast, data in memory, the official read and write performance of 100 thousand /S, and machine performance is also related
  2. Data structure server for key-value pairs
  3. Rich features: see above features
  4. Simple and stable: single threaded
  5. Persistence: In the event of a power failure or machine failure, data may be lost and persisted to the hard disk
  6. Master-slave replication: Implement multiple Redis copies of the same data
  7. High availability and distributed: The Sentinel mechanism implements high availability and ensures redis node failure detection and automatic migration
  8. Client languages: Java, PHP, Python, C, C ++, nodeJS, etc

1.3 High Performance of Redis

  1. Pure memory access
  2. Non-blocking I/O (using multiplexing)
  3. Single thread avoids thread cutting

1.3 Redis Usage Scenarios

1. Cache: Proper use of cache speeds up data access and reduces pressure on back-end data sources

2. Leaderboard: ranking according to popularity and release time, mainly using lists and ordered collections

3, counter application: video website play number, website browse number, use Redis count

4, social network: like, step, fans, pull down refresh

5. Message queues: publish and subscribe

1.4 Basic Operations of Redis

Executable file role
  redis-server Start the redis
  redis -cli Redis command line client
  redis-benchmark Benchmarking tool
  redis-check-aof AOF persistent file detection and repair tool
  redis-check-dump RDB persistent file detection and repair tool
  redis-sentinel Start the sentry
redis-trib Cluster Cluster construction tool

2. Introduction to Redis data structure

2.1 the string

String types: can actually be strings (including XML JSON), as well as numbers (integer floating point), binary (image audio video), maximum 512MB

The command note
set age 23 ex 10 Expiration in 10 seconds PX expires in 10000 milliseconds
setnx name test  If the key name does not exist, 1 is returned. Failure 0 in existence
set age 25 xx   If the age key exists, 1 is returned successfully
get age  Return value if there is, nil if there is not
set country china city beijing Batch set value
mget country city address   Batch to obtain

Note: If the mget command is not available, the get command must be executed n times

The command note
incr age     Must be an integer incrementing by 1, non-integer return error, no age key incrementing from 0 returns 1
decr age   The integer age minus 1
incrby age 2 Integer age + 2
decrby age 2 Integer age – 2
Ncrbyfloat score of 1.1 Floating point score + 1.1
append name world Additional instructions
getrange name 2 4 Intercept string

2.2 the hash (Hash)

2.2.1 Hashing objects

The hash structure of Redis is the same as that of JAVA. We can write hot data from some database to Redis. Such as:

1. User table data is as follows:

2, store to Redis, how to use string to complete the storage operation?

Hash is a mapping table of string fields and values. Hashes are particularly suitable for storing objects

Operation command: hmset user:1 name Dk age 18

2.2.2 Common Hash Commands

The command note
hset key field value  Hset user:1 name Dk// Return 1 on success and 0 on failure
hget user:1 name The values
hdel user:1 age  Delete value only
hlen user:1  Calculate the number of
hmset user:2 name Dk age 23 sex boy Batch set value
hmget user:2 name age sex Bulk values
hexists user:2 name Determine whether the field exists
hkeys user:2 Get all fields
hvals user:2 Bulk values
hgetall user:2 Get all fields and values in user:2
hincrby user:2 age 1  Add 1
hincrbyfloat user:2 age 2 Add 2 floats

2.2.3 Advantages of Storing Hash objects

1, native: set user:1:name Dk;

               set user:1:age  23;

               set user:1:sex boy;

Advantages: Simple and intuitive, with one value for each key

Disadvantages: Too many keys, too much memory, too scattered user information, not used in production environment

2. Serialize the object into Redis

      set user:1 serialize(userInfo);

Advantages: Simple programming, high memory usage if using serialization

Disadvantages: There is some overhead for serialization and deserialization. When updating attributes, userInfo needs to be taken out for deserialization, and then serialized to Redis after updating

3, use the hash type:

        hmset user:1 name Dk age 23 sex boy

Advantages: Simple and intuitive, reasonable use can reduce memory space consumption

Disadvantages: You need to control ziplist and Hashtable conversions, and hashtable consumes more memory erialize(userInfo);

2.2.4 Internal coding

The internal encoding of hash is mainly ziplist< compressed list > and hashtable< hashtable >, which can be described in separate sections later if you are interested

When the number of fields is small and there is no large value, the internal code is ziplist

For example: hmset user:3 name Dk age 24; Object Encoding User :3 // Returns ziplist

When the value is greater than 64 bytes, the internal encoding changes from ziplist to Hashtable

For example, hset user:4 address “FSGST64 bytes”; Object Encoding User :3 // Returns hashTable

2.3 The list of

2.3.1 list profile

Used to store multiple ordered strings, a list can store up to 2 to the power of 32 minus 1 element

Because of order, you can get elements by index subscript or a list of elements within a range, and list elements can be repeated

2.3.2 list Common commands

The command note
rpush Dk c b a Insert CBA from right to left, returning the value 3
lrange Dk 0 -1  Get all the elements of the list from left to right and return C, B, a
lpush key c b a Insert CBA from left to right
linsert Dk before b teacher Insert teacher before b, after after, and use lrange Dk 0-1 to see
lrange key start end Index subscripts: 0 to N-1 from left to right
lindex Dk -1 Returns the right-most end of a, and -2 returns b
llen Dk  Returns the current list length
lpop Dk Delete the leftmost element c
rpop Dk Delete the rightmost element A

2.4 the collection

2.4.1 Collection Application Scenarios

User tagging, social networking, searching for people with common interests, intelligent recommendations

Save multiple elements, unlike the list is not allowed to have repeated elements, and the set is unordered, a set can save at most 2 to the power of 32 minus 1 element, in addition to support the addition, deletion, but also support set intersection, union, difference set;

2.4.2 set Command:

The command note
exists user Check whether the user key value exists
sadd user a b c Insert three elements into user and return 3
sadd user a b If you add the same element again, repeat is invalid and 0 is returned
smember user Gets all elements of user and returns an unordered result
srem user a  Return 1 and remove element A
scard user  Return 2 and count the number of elements

2.4.3 Example

When we want to filter people with the same interests based on the user’s tags, to make smart recommendations, we can calculate this way

1. Add labels to users:

  sadd user:1:fav basball fball pq

  sadd user:2:fav basball fball  

.

2. Or add a user with a label

  sadd basball:users user:1 user:2

  sadd fball:users user:1 user:2

.

3. Calculate who you are interested in:

  sinter user:1:fav user2:fav

2.5 Ordered Sets ( ZSET )

2.5.1 Common Scenarios

Often used in leaderboards, such as video sites need to do leaderboards for users to upload videos, or the number of likes. Associated with a collection, cannot have duplicate members

3. Common redis commands

3.1 Common Commands

1, view all keys:

             keys *   set school enjoy   set hello world

              keys *ool   —–>   school

2, total number of keys:

Dbsize //2 keys, if there is a large number of keys, do not use this command online

3, check whether the key exists:

Exists key // Returns 1 if exists, and 0 if not

4. Key expiration:

Expire Key seconds // Set name Test expire name 10, indicating that the expire time is 10 seconds

TTL key // View the remaining expiration time

5, key data structure type:

Type KEY // Mandatory string. None is returned if the key does not exist

3.2  Redis database management

redis Database Management Mode
Select 0 Selects the database
Flushdb Clears the database
Flushall Flushall clears all data
Dbsize Data size

16 databases are supported by default. Can be thought of as a namespace

Points that are different from relational databases

  1. Redis does not support custom database nouns
  2. Authorization cannot be set separately for each database
  3. Each database is not completely isolated from each other. You can use the flushall command to flushall database data in the redis instance plane

Use select dbid to select different database namespaces. The default value of dbid ranges from 0 to 15