Make writing a habit together! This is my first day to participate in the “Gold Digging Day New Plan · April More text challenge”, click to see the details of the activity.

Redis Study Notes series consists of six articles:

  1. Redis Study Notes: Quick Start
  2. Redis study Notes: Core concepts
  3. Redis Study Notes: Performance optimization
  4. Redis learning Notes: Distributed solutions
  5. Redis learning notes: SpringBoot actual combat (with package complete code)
  6. Redis study notes: Often meet questions and answers

I wrote this series of articles in order to check and fill in the gaps, and to help more partners quickly master the core knowledge of Redis. This is the second one. Let’s start now.

In the previous quick Start, we looked at the basic operations of the five data structures in Redis. To learn more about Redis commands, or to query them at work, see the documentation below.

Redis command documentation

This article will focus on the following core concepts.

Publish/Subscribe (Pub/Sub)

Second, sorting,

Third, Redis basic transaction

4. Expired key

Publish/Subscribe (Pub/Sub)

It’s like a radio station. Publishers send messages on radio stations, which subscribers can listen to. Publishers can publish from any radio station, and subscribers can listen to multiple radio stations simultaneously.

Publish/subscribe features: listeners subscribe to channels and publishers send messages to channels. Anyone who listens to a subscription channel receives all messages sent to that channel when they connect and listen.

Common commands:

The command Simple use and description
SUBSCRIBE The SUBSCRIBE channel [channel]… Subscribe to a given channel
UNSUBSCRIBE UNSUBSCRIBE [channel [channel…]] – UNSUBSCRIBE from provided channels, or UNSUBSCRIBE from all channels if no channel is given
PUBLISH PUBLISH channel message – Publishes a message to a given channel
PSUBSCRIBE PSUBSCRIBE pattern [pattern …] – Subscribe to broadcast information to channels that fit a given pattern.
PUNSUBSCRIBE PUNSUBSCRIBE [pattern [pattern…]] – Unsubscribe provided patterns, or unsubscribe all subscribed patterns if not given

Example:

Create a subscription channel called runoobChat:

Redis 127.0.0.1:6379> SUBSCRIBE runoobChat Reading Messages... (press Ctrl-C to quit) 1) "subscribe" 2) "runoobChat" 3) (integer) 1Copy the code

Restart a Redis client, then runoobChat posts twice on the same channel, and subscribers receive the messages.

Redis 127.0.0.1:6379> PUBLISH runoobChat "redis PUBLISH test" (integer) 1 redis 127.0.0.1:6379> PUBLISH runoobChat "Learn redis by runoob.com" (integer) 1 # The client will display the following message: 1) "message" 2) "runoobChat" 3) "redis PUBLISH test" 1) "message" 2) "runoobChat" 3) "Learn redis by runoob.com"Copy the code

Disadvantages:

1. In older versions of Redis, clients that subscribed to channels but did not read the sent messages fast enough could cause Redis itself to maintain large buffers.

If this buffer becomes too large, it can cause Redis to slow down sharply or crash, possibly causing the operating system to kill Redis, and possibly even causing the operating system to crash.

Newer versions of Redis don’t have this problem and will disconnect subscription clients that can’t keep up.

2. Data transmission reliability is poor. In any type of network system, connection failures must be considered. Usually, this is done by connecting one side or the other side incorrectly after re-connecting.

The Python Redis client typically handles connection problems well by automatically reconnecting on failure, automatically handling connection pooling, and so on.

But for clients that have subscribed, if the client disconnects and sends a message before reconnecting, the client will never see the message, which means some data will be lost.

Second, sorting,

Sorting in Redis is similar to sorting in other languages. We use sort for sorting operations.

The command describe
sort SORT source-key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern…]]. [ASC \ DESC] [ALPHA] [STORE dest-key] – Sorts the input LIST, SET, or ZSET according to the options provided and returns or stores the results.

A simple example is as follows:

> > > conn. Rpush (' sort - input, 23, 15, 110, 7) 4 > > > conn. Sort (' sort - input) [' 7 ', '15', '23', '110'] # can be number sequences on the project. > > > conn. Sort (' sort - input, alpha = True) [' 110 ', '15', '23', '7'] # for project sorted in alphabetical order > > > conn. Hset (' d - 7 ', 'field', 5) 1L >>> conn.hset('d-15', 'field', 1) 1L >>> conn.hset('d-23', 'field', 9) 1L >>> conn.hset('d-110', 'field', Conn. Sort ('sort-input', by='d-*->field') ['15', '110', '7', '23'] # Sort data by HASH field >>> conn.sort('sort-input', by='d-*->field', get='d-*->field') ['1', '3', '5', '9']Copy the code

Third, Redis basic transaction

In Redis, A basic transaction provides A client with the ability to execute multiple commands A, B, C… Other clients cannot interrupt their opportunities. This is different from relational database transactions, which can be partially executed and then rolled back or committed.

In Redis, each command is executed as part of the base command passing multiple/execution transactions one after another until they complete. When finished, other clients can execute their commands.

MULTI, EXEC, DISCARD, WATCH, and UNWATCH are Redis transaction related commands. Transactions can execute more than one command at a time with two important guarantees:

  • A transaction is a single isolated operation: all commands in the transaction are serialized and executed sequentially. The transaction will not be interrupted by command requests from other clients during execution.
  • A transaction is an atomic operation: all or none of the commands in a transaction are executed.
The command describe
MULTI Marks the start of a transaction block.
EXEC Execute all commands within the transaction block.
DISCARD Cancels the transaction, abandoning all commands in the transaction block.
WATCH Monitor a key (or keys) and interrupt the transaction if the key (or keys) is changed by another command before the transaction executes.
UNWATCH Unmonitor all keys with the WATCH command.

MULTI, EXEC example:

Redis 127.0.0.1:6379> MULTI OK redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days" QUEUED redis 127.0.0.1:6379> GET book-name QUEUED redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series" QUEUED redis 127.0.0.1:6379> SMEMBERS tag QUEUED redis 127.0.0.1:6379> EXEC 1) OK 2) "Mastering C++ in 21 days" 3) (integer) 3 4) 1) "Mastering Series" 2) "C++" 3) "Programming"Copy the code

About WATCH and UNWATCH

WATCH makes the EXEC command conditional: a transaction can only be executed if none of the monitored keys are modified, and if this condition is not met, the transaction will not be executed.

The WATCH command can be called multiple times. Monitoring of keys takes effect from after WATCH execution until EXEC is called.

Users can also monitor any number of keys in a single WATCH command, like this:

redis> WATCH key1 key2 key3 OK
Copy the code

When EXEC is invoked, monitoring of all keys is removed, regardless of whether the transaction executes successfully.

In addition, when the client disconnects, the client’s monitoring of the key is also removed.

You can manually unmonitor all keys using the UNWATCH command with no arguments. For transactions that require multiple key changes, sometimes the program needs to lock multiple keys at the same time and then check whether the current values of these keys match the program’s requirements. When the value does not meet the requirement, the UNWATCH command can be used to cancel the current monitoring of the key, abandon the transaction halfway, and wait for the transaction’s next attempt.

4. Expired key

When writing data to Redis, the data may expire within a certain period of time, such as token. If we need to delete the entire key after the specified time expires, we can use expire. When we say that a key has time to live or that it will expire at a given time, Redis will automatically delete the key when it expires.

Expired keys are great for handling cleanup of cached data.

The command describe
PERSIST PERSIST key-name – The expiration time of the key to be deleted
TTL TTL key-name – Returns the remaining time before the key expires.
EXPIRE EXPIRE key-name seconds – Sets the key to EXPIRE within a given number of seconds.
EXPIREAT EXPIREAT key-name timestamp – Sets the expiration time to the given Unix timestamp.
PTTL PTTL key-name – Returns the number of milliseconds before the key expires (available in Redis 2.6 and later).
PEXPIRE PEXPIRE key-name milliseconds – sets the key to expire in a given number of milliseconds (available in Redis 2.6 and later).
PEXPIREAT PEXPIREAT key-name timestamp-milliseconds – Sets the expiration time to the given Unix timestamp in milliseconds (available in Redis 2.6 and later).

A simple example is as follows:

>>> conn.set('key', 'value')
True
>>> conn.get('key')
'value'

>>> conn.expire('key', 2)
True
>>> time.sleep(2)
>>> conn.get('key')

>>> conn.set('key', 'value2')
True

>>> conn.expire('key', 100); conn.ttl('key')
True
100
Copy the code