SoFunction
Updated on 2025-05-13

SpringBoot uses Redisson to roll back the Redis transaction

1. Redisson's transaction support

Redisson provides distributed transaction functions, and its core mechanism is:

  • Command Queue: The Redis command in the transaction is cached in the client queue until batch execution is performed at commit.
  • Rollback mechanism: If an exception occurs before the transaction is committed, Redisson will discard the commands in the queue and implement rollback.

2. Integration with Spring transactions

passRedissonTransactionManagerRedisson is able to deal with Spring's declarative transactions (@Transactional) Seamless integration:

  • Configuration example
@Configuration
public class RedissonConfig {
    @Bean
    public RedissonTransactionManager transactionManager(RedissonClient redissonClient) {
        return new RedissonTransactionManager(redissonClient);
    }
}
  • Transaction usage
@Transactional
public void transactionalMethod() {
    RMap<String, String> map = ("myMap");
    ("key1", "value1"); // The command enters the queue, but is not executed immediately    // If an exception is thrown here, the transaction is rolled back, and the Redis operation will not take effect    someDatabaseOperation(); // Assume that the database is operated at the same time}

3. Conditions for transaction rollback

  • When the method is thrownunchecked exception(likeRuntimeException) Spring will automatically roll back the transaction.
  • If you need to roll backchecked exception, need to pass@Transactional(rollbackFor = )Specified.

4. Important precautions

  • Cross-resource transactions: Redis transactions and database transactions are independent. If you need to ensure strong consistency across Redis and databases, you need to introduce them.Distributed transaction scheme(such as Seata or JTA).
  • Performance impact: Redis transactions are implemented through command queues. Transactions that have not been committed for a long time may cause connection blockage, and transaction boundaries need to be designed reasonably.
  • Watch command restrictions: Redisson transactions do not support Redis nativeWATCHCommand, need to be used insteadRLockorRReadWriteLockAchieve optimistic locks.

5. Manual transaction management (not recommended)

If fine-grained control is required, you can use Redisson'sRTransactionObject:

RTransaction transaction = (());
try {
    ("myMap").put("key1", "value1");
    ();
} catch (Exception e) {
    ();
}

Summarize

Redisson supports transaction rollback in Spring Boot, but make sure:

  1. Correct configurationRedissonTransactionManager
  2. use@TransactionalAnnotation mark transaction method.
  3. Avoid misuse of local transactions across resources (such as Redis + databases) and upgrade to a distributed transaction scenario if necessary.

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