Liferay同时连接多个数据库及其事务问题

    Liferay运用的是spring框架,从早期版本开始,就可以同时连接多个数据库应用,但是在Liferay的文档还是代码中都没有关于同时连接多个数据库的说明,从<st1:chsdate isrocdate="False" w:st="on" year="1899" day="30" islunardate="False" month="12">4.2.0</st1:chsdate>的版本开始出现了连接多个数据库的文档(请参照liferay wiki:http://wiki.liferay.com/index.php/Connecting_to_Another_Datasource/Database),代码中也有相应的明确定义。<o:p></o:p>

       首先我们来看他的liferay-service-builder_4_2_0.dtd,在Element column中增加了两项属性data-source CDATA #IMPLIED和    session-factory CDATA #IMPLIED,对于这两个属性文档中是这样描述的:

The data-source value specifies the the data source target that is set to the    
    
persistence class. The default value is the Liferay data source. This is used in    
    
conjunction with session-factory.    
    
   
    
The session-factory value specifies the the session factory that is set to the    
    
persistence class. The default value is the Liferay session factory. This is    
    
used in conjunction with data-source   

<o:p></o:p> 由此可见,通过定义这两个属性,可以把自定义的某个entity指定不同的datasource和sessionfactory,从而实现连接不同的数据库。例如,我们按照wiki中的文章增加了一个ext-spring-training.xml的定义文件,然后我们就可以把entity的datasource指定为trainingDataSource,sessionfactory指定为trainingSessionFactory。<o:p></o:p>

       指定了多个不同的数据库,取得了不同的connection,那从不同的sessionfactory得到了不同的transaction instance,大家担心的就是分段式事务问题,而liferay的事务处理是由spring support的,我们可以先看看spring中的PlatformTransactionManager

public interface PlatformTransactionManager {    
    
  TransactionStatus getTransaction(TransactionDefinition definition)    
    
  throws TransactionException;    
    
  void commit(TransactionStatus status) throws TransactionException;    
    
  void rollback(TransactionStatus status) throws TransactionException;    
    
}   

当程序由于事务问题抛出异常的时候,spring文档是这样描述的: 

Again in keeping with Spring's philosophy, the TransactionException that can be thrown by any of the<o:p></o:p>

PlatformTransactionManager interface's methods is unchecked (i.e. it extends the<o:p></o:p>

java.lang.RuntimeException class). Transaction infrastructure failures are almost invariably fatal. In rare<o:p></o:p>

cases where application code can actually recover from a transaction failure, the application developer can still<o:p></o:p>

choose to catch and handle TransactionException. The salient point is that developers are not forced to do so.

看spring的源码,你会发现当程序在运行过程中抛出unchecked exception的时候,transaction会设为rollback only的status从而回滚事务。所以我们设想只要抛出unchecked exception的时候,事务很同时回滚。通过测试,事务不能同时回滚。主要原因是因为处于不同的sessionfactory中,就是说两个事务之间没有任何的联系。<o:p></o:p>

分布式事务,ejb方有个很好的解决方案,至于在liferay中如何运用,还需时间去研究。<o:p></o:p>

<o:p></o:p>

       在liferay这样的活动性高的开源平台下做开发,未免升级时候会遇到种种问题,其中一个就是数据库的升级问题,所以一个很好的方案是把liferay的数据库和业务数据库分开。虽然事务没有按预期测试成功,但是对于多个没有事务关联的数据库来说,这个是个很好的解决方案,而且连接不同数据库是通过配置完成,对开发人员是透明的。希望这篇文章能对运用liferay的朋友有帮助。同时,欢迎大家针对连接多个数据库的方案特别是事务问题作出讨论。<o:p></o:p>

 

相关推荐