日期:2014-05-16  浏览次数:20637 次

分布式数据库配置(转载)
在SpringSide 3社区中,不断有人提出多数据源配置的问题,但是时至今日却一直没有一个完美的答案。经过一个星期的折腾,我总算搞清楚了在SpringSide 3中配置多数据源的各种困难并加以解决,在这里,特地把我配置SpringSide 3项目中多数据源的过程写出来,与大家分享。

我使用的SpringSide的版本是江南白衣最新发布的3.1.4版,在上一篇博文中,记录了我折腾的全过程,感兴趣的朋友可以看看:
http://www.blogjava.net/youxia/archive/2009/07/12/286454.html

下面进入正题:

结论:在基于SpringSide 3的项目中,如果要使用多个数据库,首先要配置多个数据源,然后配置多个SessionFactory,这本身没有问题,但是一涉及到事务,问题就来了,在多数据源的环境下,必须使用JTATransactionManager,而使用JTATransactionManager,就必须得有提供JTA功能的应用服务器或提供JTA功能的别的什么组件。

以上结论绝对正确,是属于SpringSide 3中关于使用多个数据库的最权威解答,下面来看具体过程:

方法一、使用GlassFish应用服务器

1、准备GlassFish服务器,下载地址为http://download.java.net/glassfish/v3/promoted/,我选择的是08-Jul-2009 17:20发布的大小为72M的latest-glassfish.zip,这里需要强调的一点是千万不要选择latest-glassfish-windows.exe这个版本,因为这个版本在Windows环境中只安装GlassFish而不提供合理的初始化配置,对于新手来说使用门槛太高,而ZIP版一解压缩就可以使用,其服务器是配置好了的;

2、在GlassFish中配置多个数据源,启动GlassFish后,访问4848端口就可以进入到GlassFish的管理界面,在其中配置两个数据源,其资源名称分别为jdbc/dataSourceContent和jdbc/dataSourceIndex,如下图:


3、在项目中配置多个DataSource和多个SessionFactory,并选择JTATransactionManager作为事务管理器,这里的DataSource是使用JNDI查找从应用服务器中获得的。下面是我项目中的applicationContext.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
    default-lazy-init="true">

    <description>Spring公共配置文件 </description>

    <!-- 定义受环境影响易变的变量 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <!-- 标准配置 -->
                <value>classpath*:/application.properties</value>
            </list>
        </property>
    </bean>

    <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
    <context:component-scan base-package="cn.puretext" />

    <!-- 数据源配置,使用应用服务器的数据库连接池 -->
    <jee:jndi-lookup id="dataSourceContent" jndi-name="jdbc/dataSourceContent" />
    <jee:jndi-lookup id="dataSourceIndex" jndi-name="jdbc/dataSourceIndex" />

    <!-- Hibernate配置 -->
    <bean id="sessionFactoryContent" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSourceContent" />