[英]Transaction Control over a Connection Pool
我有一个多线程应用程序,其中正在解析文件并将其插入数据库中-我有一个用于写入数据库的数据库连接池-我需要对解析/写入整个操作添加事务控制,即在解析过程中出现任何错误的情况下/ db-insert操作,我想回滚需要回滚我的部分db写操作的整个操作-有什么方法可以做到这一点?
You'll need to take the connection out of the pool, start the database transaction on it, and keep it out of the pool for the duration of the transaction. 您需要将连接移出池,在其上启动数据库事务,并在事务期间将其保持在池外。 You'll only return it back to the pool once you finish (commit or rollback) the transaction.
完成(提交或回滚)事务后,您才将其返回到池中。
This obviously means that you cannot run more transactions in parallel than you have connections in your pool. 显然,这意味着与池中的连接相比,您不能并行运行更多的事务。 If you cannot accept this limitation, you'll have to devise your own workaround that doesn't rely on database transactions (eg using a "stage" table that accepts data with some unique identifier, then moving it into the main storage at once, plus a task to delete stale data).
如果您不能接受此限制,则必须设计自己的不依赖数据库事务的解决方法(例如,使用“阶段”表来接受带有某些唯一标识符的数据,然后立即将其移至主存储中,加上删除旧数据的任务)。
I recommend reading on Spring's transaction manager for an inspiration. 我建议阅读Spring的事务管理器以获取启发。
If I understand it correctly you have an application which split the file into several parts, each part is parsed by a different thread and each uses its own connection from the pool. 如果我对它的理解正确,那么您有一个将文件拆分为几个部分的应用程序,每个部分都由不同的线程进行解析,并且每个部分都使用来自池的自己的连接。
I think the transaction manager could help here if you are fine to use XA transactions. 如果您可以使用XA交易,我认为交易经理可以在这里提供帮助。 Each of the connection would form a separate transaction branch thus each of the thread would then work on a separate participant of the transaction.
每个连接将形成一个单独的事务分支,因此每个线程将在该事务的一个单独参与者上工作。 At the end, 2PC would ensure to get all committed or rolled-back.
最后,2PC将确保获得所有提交或回滚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.