手动创建的多个数据源的事务管理 [英] Transaction Management for multiple datasources created manually

查看:30
本文介绍了手动创建的多个数据源的事务管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,其中我必须根据从客户端传递的客户 ID 连接到不同的数据库.所有数据库的架构都是相同的.它是一种多租户应用程序.由于我不知道会有多少客户,我无法使用xml配置来静态创建数据源,因此我必须手动创建数据源.

I am working on an application wherein I have to connect to different database depending upon an customer id that is passed from the client side. The schema for all the databases is same. It is a kind of multi-tenant application. Since I don't know how many customers will be there, I cannot use xml configuration to statically create the datasources, hence I have to create datasources manually.

我们使用 Spring JdbcTemplate 连接到数据库,连接参数来自另一个保存应用程序配置的数据库.我能够正确连接到数据库,但方法调用没有在事务中发生.以下是仅对一个数据库进行数据库连接的代码片段,我打算将其扩展到多个数据库:

We are using Spring JdbcTemplate for connecting to the databases and the connection parameter comes from another database which holds the configuration for the application. I am able to connect to the databases properly, but the method calls are not happening in a transaction. Following is the code snippet which does the database connectivity for only one database and I was going to extend it for multiple databases:

BasicDataSource datasource = new BasicDataSource();
// set database connection params
....
// create jdbcTemplate, 
jdbcTemplate = new JdbcTemplate(datasource);
// create transaction managers
PlatformTransactionManager txManager = new DataSourceTransactionManager(datasource);

我的想法是手动创建事务管理器,并以某种方式将其绑定到spring容器中,以便所有带有@Transactional注解的方法/类都可以使用此事务管理器.我无法弄清楚如何绑定 txManager,以便所有带有 @Transactional 的方法/类都将使用此事务管理器.我不确定这是否是正确的方法,我是否应该为每个数据源创建一个事务管理器,因为我不希望事务跨越多个数据库,但我希望每个服务方法调用都应该在一个事务中.注意:我所有的服务类都有@Component 和@Transactional 注解.

My idea is to create the transaction manager manually and somehow bind it in the spring container so that all the methods/classes with @Transactional annotation can use this transaction manager. I am not able to figure how do I bind the txManager, so that all the methods/classes with @Transactional will use this transaction manager. I am not sure whether this is the right way and should I be creating a transaction manager for every datasource, since, I don't want the transaction to span multiple databases, but I want that every service method call should be in a transaction. Note: All my service classes have @Component and @Transactional annotation.

我是否以正确的方式解决问题?

Am I solving the problem in the correct way?

推荐答案

可以使用 spring 的 AbstractRoutingDatasource.

You can use the spring's AbstractRoutingDatasource.

请查看以下链接.解释了 AbstractRoutingDatasource.这里的数据库是根据所选语言动态更改的.

Please check the below link. The AbstractRoutingDatasource is explained.Here database is changed dynamically based on language selected.

Spring AbstractRoutingDatasource

这篇关于手动创建的多个数据源的事务管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆