SoFunction
Updated on 2025-04-12

Redis transaction mechanism and how to use it in Springboot projects

Redis's transaction mechanism allows multiple commands to be packaged together and executed as an atomic operation. Although Redis's transactions differ from those of relational databases, it still provides a way to ensure multiple commands are executed sequentially.

The following is a detailed analysis of the Redis transaction mechanism:

1. Basic concepts of Redis transactions

Redis transactions are implemented through the following four commands:

  • MULTI: Start a transaction.
  • EXEC: Execute all commands in the transaction.
  • DISCARD: Cancel the transaction and abandon all enqueued commands.
  • WATCH: Monitor one or more keys, and if these keys are modified before the transaction is executed, the transaction will not execute.

The core idea of ​​Redis transactions is to put multiple commands into a queue and then execute them at once, in sequence.

2. Redis transaction workflow

2.1 Start transactions

useMULTICommand to start a transaction.

After the transaction is started, all subsequent commands will be placed in a queue instead of being executed immediately.

127.0.0.1:6379> MULTI
OK

2.2 Order to join the queue

After the transaction is started, all commands will be placed in the queue and wait for execution.

For example:

127.0.0.1:6379> SET key1 value1
QUEUED
127.0.0.1:6379> SET key2 value2
QUEUED

2.3 Execute transactions

useEXECCommand executes all commands in a transaction.

Redis will execute commands in the queue in order and return the execution result of each command.

127.0.0.1:6379> EXEC
1) OK
2) OK

2.4 Cancel transaction

If the transaction needs to be cancelled before the transaction is executed, you can useDISCARDOrder.

This clears the transaction queue and exits the transaction.

127.0.0.1:6379> DISCARD
OK

3. Features of Redis transactions

3.1 Atomicity

Redis transactions are atomic, which means that all commands in the transaction are either executed or all are not executed. However, Redis transactions do not support rollback. If a command fails during transaction execution, subsequent commands will continue to be executed.

3.2 Isolation

Redis transactions are isolated, and the commands in the transaction areEXECIt will not be seen by other clients before execution. Other clients only after the transaction is committed (i.e.EXECOnly after execution can the transaction result be seen.

3.3 No rollback mechanism

Redis transactions do not support rollback. If a command fails during transaction execution (for example, a syntax error), Redis does not automatically roll back the executed command. This is different from the transaction mechanism of a relational database.

3.4 Order to join the queue

After the transaction is started, all commands are placed in the queue instead of being executed immediately. Only inEXECThe commands in the queue will be executed only when the command is called.

4. WATCH command

WATCHCommands are used to monitor one or more keys. If these keys are modified by other clients before the transaction is executed, the transaction will not be executed.

WATCHAn optimistic locking mechanism is provided to solve concurrency problems.

4.1 Using WATCH

127.0.0.1:6379> WATCH key1
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET key1 value1
QUEUED
127.0.0.1:6379> EXEC
(nil)  # if key1 Modified by other clients,Transactions will not be executed

4.2 Cancel WATCH

useUNWATCHThe command can cancel monitoring of all keys.

127.0.0.1:6379> UNWATCH
OK

5. Limitations of Redis transactions

5.1 Rollback is not supported

Redis transactions do not support rollback. If a command fails during transaction execution, Redis will not automatically roll back the executed command.

5.2 Command error and runtime error

  • Command error: If a command in a transaction has a syntax error (for example, the command does not exist), the entire transaction will not be executed.
  • Runtime error: If a command in a transaction errors when executing (for example, executing a stringINCR), then only this command will fail, and other commands will still be executed.

5.3 Performance issues

The Redis transaction will put all commands into the queue untilEXECExecute only at one time when executing. If a large number of commands are included in the transaction, it may cause excessive memory usage.

6. Application scenarios of Redis transactions

6.1 Batch operation

When multiple commands need to be executed at once, transactions can be used to ensure that these commands are executed sequentially.

6.2 Optimistic lock

passWATCHCommands can implement optimistic locking mechanisms to ensure that keys monitored before transaction execution are not modified.

6.3 Atomic operation

Although Redis transactions do not support rollback, it still ensures atomic execution of multiple commands.

7. Comparison of Redis transactions and Lua scripts

Both Redis transactions and Lua scripts can be used to implement atomic operations, but there are the following differences between the two:

  • Transactions: Suitable for simple batch operations, but does not support complex logic.
  • Lua script: Suitable for complex business logic, supports condition judgment, looping and other operations, and scripts are executed atomically on the server side.

8. Example of Redis transaction

Here is a complete Redis transaction example:

# Monitor key1127.0.0.1:6379> WATCH key1
OK

# Start transactions127.0.0.1:6379> MULTI
OK

# Order to join the queue127.0.0.1:6379> SET key1 value1
QUEUED
127.0.0.1:6379> SET key2 value2
QUEUED

# Submit transaction127.0.0.1:6379> EXEC
1) OK
2) OK

When using Redis transaction mechanism in Spring Boot, you can useRedisTemplateorStringRedisTemplateTo operate Redis transactions.

Spring Data Redis provides support for Redis transactions, allowing you to easily use Redis transactions in Spring applications.

9. Use Redis transactions in Spring Boot

9.1 Configuring RedisTemplate

First, make sure you are configured in your Spring Boot projectRedisTemplateorStringRedisTemplate

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        (redisConnectionFactory);
        (new StringRedisSerializer());
        (new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

9.2 Using Redis Transactions

In Spring Boot, you can useRedisTemplateofexecuteMethod to perform transaction operations.executeMethod accepts aSessionCallbackorRedisCallbackParameters used to execute multiple commands in a transaction.

@Service
public class RedisTransactionService {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public void executeTransaction() {
        (new SessionCallback&lt;Object&gt;() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                // Start transactions                ();

                // Execute multiple commands                ().set("key1", "value1");
                ().set("key2", "value2");

                // Submit transaction                return ();
            }
        });
    }
}

9.3 Using the WATCH command

WATCHCommands are used to monitor one or more keys, and if these keys are modified before the transaction is executed, the transaction will not execute. Can be passedRedisTemplateofwatchMethod to implement.

@Service
public class RedisTransactionService {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public void executeTransactionWithWatch() {
        (new SessionCallback&lt;Object&gt;() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                // Monitor key1                ("key1");

                // Start transactions                ();

                // Execute multiple commands                ().set("key1", "value1");
                ().set("key2", "value2");

                // Submit transaction                return ();
            }
        });
    }
}

9.4. Transaction exception handling

In a Redis transaction, if a command fails to execute, the transaction will not roll back, but will continue to execute subsequent commands. Therefore, possible exceptions need to be handled in the code.

@Service
public class RedisTransactionService {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public void executeTransactionWithExceptionHandling() {
        (new SessionCallback&lt;Object&gt;() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                try {
                    // Start transactions                    ();

                    // Execute multiple commands                    ().set("key1", "value1");
                    ().set("key2", "value2");

                    // Submit transaction                    return ();
                } catch (Exception e) {
                    // Handle exceptions                    ();
                    throw e;
                }
            }
        });
    }
}

9.5. Annotation-driven transaction management

Spring Data Redis support is passed@TransactionalAnnotations to manage Redis transactions. Transaction management needs to be enabled in the configuration class.

@Configuration
@EnableTransactionManagement
public class RedisConfig {

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();
        (redisConnectionFactory);
        (new StringRedisSerializer());
        (new GenericJackson2JsonRedisSerializer());
        (true); // Enable transaction support        return template;
    }

    @Bean
    public PlatformTransactionManager transactionManager(RedisConnectionFactory redisConnectionFactory) {
        return new DataSourceTransactionManager();
    }
}

Then use it in the Service class@TransactionalAnnotation to mark transaction methods.

@Service
public class RedisTransactionService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Transactional
    public void executeTransactionWithAnnotation() {
        ().set("key1", "value1");
        ().set("key2", "value2");
    }
}

Summarize

When using Redis transaction mechanism in Spring Boot, you can useRedisTemplateofexecuteMethods to manage transactions manually, or through@TransactionalAnnotations implement declarative transaction management.

useWATCHCommands ensure the atomicity of transactions and avoid race conditions. In practical applications, it is necessary to choose appropriate transaction management methods based on business needs, and pay attention to exception handling and performance optimization.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.