I heard that searching “Java Fish Boy” on wechat will improve my skills to the next level

(a) The concept of transactions

When it comes to advanced applications of databases, it is inevitable to talk about transactions. If you are familiar with mysql, you must be familiar with transactions. Simply speaking, transactions are the control of a sequence of database operations either all executed or none executed. Today we’ll look at how transactions are executed and used in Redis.

(2) Operation of Redis transaction

In mysql, transactions are executed in three steps:

Begin Start the transaction commit Commit the transaction rollback RollbackCopy the code

In Redis, transactions are executed in three main steps

Multi Start transaction Sets the start position of a transaction. All subsequent commands are added to the transactionexecDiscard Cancels the transaction and places it in multi andexecbetweenCopy the code

As you can see, all instructions in the transaction start executing only after exec executes. However, transactions in Redis do not guarantee atomicity. When we start a transaction in Multi, if there is an error in the code before the transaction is executed, the error instruction will not be executed and other instructions will continue to execute normally.

(3) the lock

Locking is a very important technology to realize database concurrency control. Redis also has locking mechanism.

3.1 Monitoring lock:

// Watch key1 key2... / / unlock unwatchCopy the code

Add a monitor lock to a key that terminates transaction execution if the key changes before exec:Change the value of name in the other clientRe-executing the transaction will find that the transaction has been terminated

3.2 Distributed Lock:

Use setnx to set a public lock

Set lock setnx lock-key value to unlock del lock-keyCopy the code

When a public lock is placed on a key, everyone except the person who set the lock has to wait outside. Only after the lock is unlocked can anyone else do the same.

3.3 Deadlock solution

When the lock cannot be unlocked due to downtime, the rest of the team has to wait. To solve this problem, we can set a time limit for the lock. If the lock is not released, the system will delete the lock:

expire lock-key second
pexpire lock-key milliseconds
Copy the code

Because the operation is usually millisecond or microsecond, the lock time should not be set too long. In actual development, we would add a lifecycle to the distributed lock as well.