First, the same cache, with map can not?

  1.  Redis can store dozens of gigabytes of data, can Map?

  2. Redis caches can be locally persisted, can Map?

  3. Redis can be used as a distributed cache and Map can only be cached in the same JVM;
  4.  Redis supports millions of concurrencies per second, can Map?
  5.  Redis has an expiration mechanism, does Map?

  6. Redis has a rich API that supports a very wide range of application scenarios, is Map OK?

 Second, why is Redis single-threaded?

  1.  The code is clearer and the processing logic is simpler;

  2. There is no need to consider various locking issues, there are no locking and releasing operations, and there are no performance issues due to the possibility of deadlocks;
  3.  There is no multi-thread switching that consumes CPU;

  4. It is not possible to take advantage of multi-core CPUs, but it can be improved by opening a few more Redis instances;

 Third, is Redis really single-threaded?

  1. Before Redis 6.0 it was single-threaded, after Redis 6.0 it started to support multi-threading;

  2. Redis uses epoll-based multiplexing internally, and it is also possible to deploy a few more Redis servers to solve the single-threaded problem;
  3.  The main performance bottlenecks in Redis are memory and networking;

  4. Memory is good, just add a memory stick, and the network is the big problem, so Redis6 memory is good, just add a memory stick;

  5. And it’s the network that’s the big problem, so Redis 6.0 introduces the concept of multithreading that

  6. Redis 6.0 introduces multi-threading in network IO processing, such as reading and writing network data and protocol parsing, etc. It should be noted that the core module that executes the commands is still single-threaded.

 Redis advantages and disadvantages

 1. Advantages

  1. Redis is a KV database and MySQL is a relational database, Redis is faster;

  2. Redis data operations are mainly in memory, MySQL mainly stores data on the hard disk, Redis is faster;

  3. Redis also supports persistence (RDB + AOF), Redis supports data asynchronous memory data persistence to the hard disk to avoid Redis downtime data loss problems;

  4. Redis is extremely high performance, with 110,000 reads/second and 81,000 writes/second;

  5. Redis is rich in data types and supports not only KV key-value pairs, but also list, set, zset, hash and other data structures for storage;

  6. Redis supports data backup, i.e. master-slave mode data backup;
  7.  Redis supports simple transactions where operations satisfy atomicity;
  8.  Redis supports read-write separation to share the pressure of reads;
  9.  Redis supports sentinel mode for automatic failover;
  10.  Single-threaded operation avoids frequent context switching;
  11.  A non-blocking I/O multiplexing mechanism is used for excellent performance;

 2. Disadvantages

  1.  Data is stored in memory, which is prone to data loss;
  2.  The storage capacity is limited by the memory and only a small amount of frequently used data can be stored;
  3.  Cache and database double write consistency issues;

  4. When used for caching, it is prone to memory penetration, cache hit, and cache avalanche;

  5. After modifying the configuration file, you need to perform a reboot to synchronize the data from the hard disk to the memory, which consumes a long time, and Redis can’t provide services during the time of data synchronization;

 V. Redis common business scenarios

  1. Redis is a memory-based nosql database that can be persisted in the form of a new thread, without affecting Redis single-threaded read and write operations
  2.  Fetch the latest N data from the list
  3.  Simulate scenarios like tokens that require an expiration time to be set
  4.  Publishing Subscription Messaging System
  5.  Timer, Counter

  6. Cache acceleration, distributed sessions, leaderboards, distributed counters, distributed locks;

  7. Redis supports features such as transactions, persistence, LUA scripting, publish/subscribe, cache elimination, and streaming technology;

 Redis common data types

 1. String

 (1) Introduction to String

String is the most basic key-value structure, key is a unique identifier, value is a specific value, value is not only a string, but also can be a number (integer or floating point), value can hold up to 512M data length.

 (2) Application Scenarios

 ① As a cached database

In the Java management system system, most of them are using MySQL to store data, redis as a cache, because Redis has the characteristic of supporting high concurrency, usually can play a role in accelerating read and write and reducing the pressure on the database server, most of the requests will be the first request for Redis, if there is no data in the Redis, and then request the MySQL database, and then cached to the Redis for the next use.

 ② Counter

Redis string has a command INCR key , incr command will be self-incrementing operation on the value, such as CSDN article reading, video playback, can be counted by Redis, every reading +1, at the same time, the data will be stored asynchronously to the MySQL database, to reduce the write pressure of the MySQL server.

 ③ Shared session

In a distributed system, each user request will generally visit a different server , which will lead to the problem of session desynchronization , then, generally use Redis to solve this problem , the session will be deposited into Redis, use the time from Redis can be removed .

 ④ Distributed locks

  1.  setnx key value, add lock
  2.  del key, release the lock

 (3) Key operation command

 (4) set key value

SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]

  1.  EX seconds, set the expiration time in seconds.

  2. PX milliseconds, set the expiration time in milliseconds

  3. EXAT timestamp-seconds, sets the expiration time in seconds UNIX timestamps

  4. PXAT timestamp-milliseconds, sets the expiration time in milliseconds for UNIX timestamps
  5.  NX, set key value when key does not exist
  6.  XX, set key value when key exists
  7.  KEEPTTL, retains the survival time of the specified key before setup

  8. GET, return the original value of the specified key, if the key does not exist return nil


 command is not case-sensitive, while the key is case-sensitive.

help : View the operation commands related to the current type.

Since the SET command options can replace SETNX, SETEX, PSETEX, GETSET, it is possible that in future versions of Redis these commands will be deprecated and finally removed。

 (5) Setting multiple key values at the same time

 (6) Get the value in the specified interval range

 getrange, setrange.

 (7) Increase or decrease in value

  1.  INCR key, incremental number

  2. INCRBY key increment, increment by the specified value
  3.  DECR key, decremented value

  4. DECRBY key decrement, specifies that the specified value is decremented

 (8) Get the length of the string, content appending

  1.  STRLEN key, get the length of the value
  2.  APPEND key value, content appending

 2. List

 (1) Introduction to List

List lists are simple lists of strings, sorted by insertion order, and you can add elements to a List list from the head or the tail.

The maximum length of a list is 2^32 – 1, which means that each list supports more than 4 billion elements.

The main functions are push/pop, generally used in stacks, queues, message queues and other scenarios.

  1.  Both left and right can be inserted to add;
  2.  If the key does not exist, create a new linked table;
  3.  If the key exists, add new content;
  4.  If the values are all removed, the corresponding keys will also disappear;

It has a bi-directional chained table at the bottom, which has high performance for operations on both ends, and poorer performance for operations on nodes in the middle via index subscripts.

 (2) Application Scenarios

 ① Message Queue

Use lpush + rpop or rpush + lpop to implement a message queue. Redis also supports blocking operations, using the block command to implement a blocking queue when popping elements.

 ② Use as a stack

Use lpush+lpop or rpush+rpop to implement the stack.

 ③ List of Articles

 (3) Common commands

 3. Hash

 (1) Introduction to hash

A hash is a collection of key-value pairs (key – value), and a value is also a hash, equivalent to Map<String,Map<Object,Object>> .

 (2) Common Scenarios

Due to the special data structure, hash is generally used as a storage bean, and the data structure of String+JSON stores specific application scenarios.

 (3) Common commands

 4. Set

 (1) Introduction to the Set type

The Set type is an unordered and unique collection of keys and values that are not stored in the order in which they are inserted.

A set can store up to 2^32-1 elements. Concepts and math in a set is basically similar to the set, can be intersection, union, difference, etc., so the Set type in addition to supporting the set of additions, deletions, changes and checks, but also supports multiple sets of intersection, union, difference.

 (2) Application Scenarios

 ①Same friends can see

In the circle of friends scenario, for the function of likes and comments, the same and also visible functions are realized through intersection.

 ② Shared Concerns, Shared Preferences

 ③ Drawing function

 (3) Common commands

 5. Zset

 (1) Introduction to Zset type

The Zset type (ordered set type) has an additional sorting attribute, score, compared to the Set type. For an ordered set ZSet, each stored element is equivalent to two values, an ordered combination of element values and a sorted value.

An ordered set retains the property that a set cannot have duplicate members (scores can be duplicated), but the difference is that elements in an ordered set can be sorted.

zset k1 score1 v1 score2 v2

 (2) Application Scenarios


Record the number of likes by score, and then sort according to the score to realize the function of leaderboard.

 ② Delayed Message Queue

Order system, after placing an order, you need to perform the payment operation within 15 minutes, otherwise the order will be canceled automatically.

The time after 15 minutes after the order is placed is used as score and the order is stored in Redis as value, the consumer polls to consume and if the consumed is greater than or equal to the score, the order is canceled.

 (3) Zset common commands

 6. BitMap

 (1) Introduction to Bitmap

Bitmap, i.e. bitmap, is a string of consecutive binary arrays (0s and 1s) that can be used to locate an element by an offset.BitMap is set 0|1 by the smallest unit bit, representing the value or state of an element, with a time complexity of O(1).

 (2) Application Scenarios

Since the bit is the smallest unit in a computer, using it for storage will be very space-efficient, especially for scenarios where large amounts of data are used and binary statistics are used.

 ① Check-in statistics

 ② Determine whether the user is logged in or not

 ③ Statistics of people who have continuously studied and punched the clock

 (3) BitMap common commands

 7. BitField

The bitfield command allows you to manipulate multiple bits at once. It performs a series of operations and returns an array of responses, the elements of which are the results of the corresponding operations in the parameter list.

 8. HyperLogLog

 (1) Introduction to HyperLogLog

Redis HyperLogLog is a new datatype added in Redis version 2.8.9. It is a dataset type used for “counting bases”, which means counting the number of non-repeating elements in a set. However, it is important to note that HyperLogLog is a statistical rule based on probability and is not very accurate, with a standard miscalculation rate of 0.81%.

So, in short HyperLogLog provides imprecise de-duplication counting.

The advantage of HyperLogLog is that the memory space required to compute the base is always fixed and small when the number or size of input elements is very, very large.

In Redis, each HyperLogLog key only costs 12 KB of memory to compute a base of nearly 2^64 different elements, making HyperLogLog very space-efficient compared to the Set and Hash types, which consume more memory as more elements are added.

 (2) Application Scenarios

 Millions of web UV counts

 (3) Common commands

  1.  pfadd key element, add element

  2. pfcount key, which returns an estimate of the base of the specified HyperLogLog;

  3. pfmerge destkey sourcekey to merge multiple HyperLogLogs into one HyperLogLog;

 9. GEO

 (1) Introduction to GEO

Redis GEO is a new data type in Redis version 3.2, which is mainly used to store geolocation information and perform operations on the stored information.

In our daily life, we rely more and more on searching for “nearby restaurants” and hailing a cab on taxi apps, all of which are inseparable from Location-Based Service (LBS) applications, which access a set of latitude and longitude information associated with a person or an object, and are able to query adjacent latitude and longitude ranges. LBS applications access a set of latitude and longitude information associated with a person or an object, and are able to query neighboring latitude and longitude ranges, GEO is very suitable for application in LBS service scenarios.

 (2) Application Scenarios

 Location software such as Goldmind, DripTrip, and others.

 (3) Common commands

 10. Stream

 (1) Stream Introduction

Redis Stream is a new data type in Redis version 5.0, designed specifically for message queues.

Before Redis 5.0 Stream came out, message queue implementations had their own flaws, for example:

  • Publish-subscribe model, can not be persistent also can not reliably save the message, and for offline reconnection of the client can not read the history of the message defects;

  • The List implementation of message queues cannot be consumed repeatedly, a message is deleted when it is consumed, and the producer needs to implement a globally unique ID on its own.

Based on the above problems, Redis 5.0 has introduced the Stream type, which is the most important feature of this version, used to perfectly implement message queues, which supports message persistence, automatic generation of globally unique IDs, support for ack confirmation of message patterns, support for consumer group patterns, etc., so as to make message queues more stable and reliable.

 (2) Application Scenarios

 message queue

 (3) Common commands

 VII. Summary

Redis is a key-value storage system that supports 10 data types, summarizing why Redis should be used instead of map as a program cache, why Redis is single-threaded, the advantages and disadvantages of Redis, and common scenarios of Redis, doing a quick primer on Redis.

By lzz

Leave a Reply

Your email address will not be published. Required fields are marked *