java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot启用MongoDB事务

浅析SpringBoot中如何启用MongoDB事务

作者:冰糖心书房

这篇文章主要为大家详细介绍了SpringBoot中如何启用MongoDB事务,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

前言

在 Spring Boot 中启用和使用 MongoDB 事务主要依赖于以下几个方面:

1.MongoDB 服务器和部署模式:

2.Spring Boot 和 Spring Data MongoDB 版本:

3.配置 MongoTransactionManager:

Spring Boot 会在检测到合适的条件时(例如,连接 URI 指向一个副本集)自动配置 MongoTransactionManager。

4.使用 @Transactional 注解:

这是在 Spring 中管理事务的标准方式。

下面是如何在 Spring Boot 中启用和使用 MongoDB 事务:

步骤 1: 确保 MongoDB 环境支持事务

确认MongoDB 服务器版本(4.0+ for replica sets, 4.2+ for sharded clusters)。

确认MongoDB 是以副本集或分片集群模式运行。

步骤 2: 添加依赖

在你的 pom.xml (Maven) 或 build.gradle (Gradle) 文件中,确保有 Spring Data MongoDB 的 starter:

Maven (pom.xml):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

步骤 3: 配置数据库连接 URI

在 application.properties 或 application.yml 中配置 MongoDB 连接 URI。关键是要包含 replicaSet 参数(如果你的 MongoDB 是副本集)。

application.properties:

spring.data.mongodb.uri=mongodb://localhost:27017,localhost:27018,localhost:27019/mydatabase?replicaSet=rs0
# 或者对于分片集群,连接到 mongos 实例
# spring.data.mongodb.uri=mongodb://mongos1:27017,mongos2:27017/mydatabase

localhost:27017,localhost:27018,localhost:27019:副本集成员地址。

mydatabase:数据库名称。

replicaSet=rs0:副本集名称。这个参数对于 Spring Boot 自动配置 MongoTransactionManager 非常重要。

步骤 4: 启用事务管理器

a) 自动配置 (推荐)

如果 spring.data.mongodb.uri 正确配置了 replicaSet 参数(或者连接的是分片集群的 mongos),Spring Boot 通常会自动为你配置一个MongoTransactionManager bean。不需要额外做配置。

b) 手动配置 (如果自动配置不生效或需要自定义)

如果需要手动配置,可以在配置类中创建一个 MongoTransactionManager bean:

import com.mongodb.client.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoTemplate; // 仅为示例,非必需

@Configuration
public class MongoConfig {

    // Spring Boot 会自动配置 MongoDatabaseFactory
    // 你只需要注入它来创建 MongoTransactionManager
    @Bean
    MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

    // 可选: 如果你也想配置一个 MongoTemplate bean
    // @Bean
    // public MongoTemplate mongoTemplate(MongoDatabaseFactory dbFactory, MongoClient mongoClient) {
    //     return new MongoTemplate(mongoClient, dbFactory.getMongoDatabase().getName());
    // }
}

注意: 通常情况下,如果你的 URI 配置正确,Spring Boot 的自动配置就足够了,你不需要手动创建这个 bean。

步骤 5: 在 Service 层使用 @Transactional

现在可以在Service 方法上使用 Spring 的 @Transactional 注解来声明事务。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // Spring的事务注解
import com.mongodb.MongoException; // 更通用的MongoDB异常
import com.mongodb.MongoTransactionException; // 事务特定异常

@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepository; // 假设你有一个 AccountRepository

    @Autowired
    private AuditLogRepository auditLogRepository; // 假设你有一个 AuditLogRepository


    /**
     * 示例:在一个事务中转账并记录日志
     * 如果任何一步失败,整个操作将回滚
     */
    @Transactional // 关键注解
    public void transferMoney(String fromAccountId, String toAccountId, double amount) {
        try {
            Account fromAccount = accountRepository.findById(fromAccountId)
                    .orElseThrow(() -> new RuntimeException("Source account not found"));
            Account toAccount = accountRepository.findById(toAccountId)
                    .orElseThrow(() -> new RuntimeException("Destination account not found"));

            if (fromAccount.getBalance() < amount) {
                throw new RuntimeException("Insufficient funds");
            }

            fromAccount.setBalance(fromAccount.getBalance() - amount);
            toAccount.setBalance(toAccount.getBalance() + amount);

            accountRepository.save(fromAccount);

            // 模拟一个可能发生的错误,以测试回滚
            // if (true) {
            //     throw new RuntimeException("Simulated error during transfer!");
            // }

            accountRepository.save(toAccount);

            // 记录审计日志
            AuditLog log = new AuditLog("Transfer of " + amount + " from " + fromAccountId + " to " + toAccountId);
            auditLogRepository.save(log);

            System.out.println("Transfer successful and logged!");

        } catch (RuntimeException e) {
            // @Transactional 会在 RuntimeException 抛出时自动回滚
            // 你可以在这里记录错误,但不需要手动回滚
            System.err.println("Transfer failed: " + e.getMessage());
            throw e; // 重新抛出,以便 Spring 能够捕获并回滚事务
        }
    }

    /**
     * 示例:只读事务
     * 对于只需要读取数据的操作,可以标记为只读,这可能有一些性能优化。
     */
    @Transactional(readOnly = true)
    public Account getAccountDetails(String accountId) {
        return accountRepository.findById(accountId).orElse(null);
    }

    // 假设的实体和仓库
    // Account.java, AuditLog.java
    // AccountRepository.java extends MongoRepository<Account, String>
    // AuditLogRepository.java extends MongoRepository<AuditLog, String>
}

工作原理:

步骤 6: 异常处理和重试 (重要!)

MongoDB 事务可能会因为写冲突 (write conflicts) 而中止。当两个并发事务尝试修改同一个文档时,就会发生这种情况。MongoDB 会中止其中一个事务,并抛出 MongoTransactionException (通常是其子类,如 MongoWriteConflictException)。

在应用程序中必须捕获这些异常并重试整个事务。

// 在调用方或者一个更高层次的Service
@Service
public class TransactionalCallerService {

    @Autowired
    private AccountService accountService;

    private static final int MAX_RETRIES = 3;

    public void performTransferWithRetry(String from, String to, double amount) {
        int retries = 0;
        boolean success = false;
        while (retries < MAX_RETRIES && !success) {
            try {
                accountService.transferMoney(from, to, amount);
                success = true; // 如果没有异常,标记成功
            } catch (MongoTransactionException e) { // 捕获事务相关的异常,特别是写冲突
                retries++;
                System.err.println("Transaction failed due to conflict, retrying (" + retries + "/" + MAX_RETRIES + "): " + e.getMessage());
                if (retries >= MAX_RETRIES) {
                    System.err.println("Max retries reached. Transfer aborted.");
                    throw e; // 或者抛出一个自定义的业务异常
                }
                // 可以考虑在此处添加短暂的延迟
                try {
                    Thread.sleep(100 * retries); // 简单的指数退避
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Retry interrupted", ie);
                }
            } catch (RuntimeException e) { // 捕获其他业务逻辑异常
                System.err.println("Transfer failed due to business error: " + e.getMessage());
                throw e; // 这些通常不需要重试
            }
        }
    }
}

总结关键点:

通过这些步骤,我们就可以在 Spring Boot 应用程序中有效的使用 MongoDB 的多文档 ACID 事务了。

到此这篇关于浅析SpringBoot中如何启用MongoDB事务的文章就介绍到这了,更多相关SpringBoot启用MongoDB事务内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文