“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The transaction

  • In our daily work, we encounter many scenarios that require interventionThe transactionTo solve the
    • Such as daily transfer, purchase of goods, refund and so on a series of operations
    • Let’s take a look atredisThe transaction
    • We are storedA == 1, let'sA ‘increments twice and finally executes the transaction

  • The specific process
    • First, when we do not execute exec, our above operations are in a transaction queue cached by Redis,

    • QUEUED is QUEUED every time we run a command

    • The transaction is executed when an exec is executed

Simulate the process of a transaction failure

  • First of all, weMULTIRepresentation is a transaction
    • willaI’m going to put 1, and then I’m going to putaI’m going to increase by one, and then I’m going tobSet to stringtest
    • willbIncrement, this is an error, because strings cannot increment
    • Now and thenaIncrement by one and execute lastexecIs an error

    When all commands enter the queue, if there is an error, it will not be rolled back. When get a, the value of A will still be increased to 3

Optimistic locking – watch

  • When our business is complex with changes to data, we can only make changes in logical business
    • soredisprovideswatch, can be inMULTIBefore usingwatchKeep an eye on the variables,
    • If thewatchAn error is reported if the variable is modified after the transaction is executednil)
    • As shown in the figure below

  • In our real business, transactions are generally maintained in code
    • Such as using SpringBoot annotations to implement transactions, if maintained in Redis is not safe
    • Because we can clearly integrate transactions with business scenarios in the code, we try to leave the business of atomic classes to the framework and logical code

Summary Redis supports transactions, but there is no rollback function in transactions. Each command is put into a queue 🦄