spring多数据源配置

最后更新:2023-10-18 21:25:23 | 状态:未完成

在XML中配置


	<bean id="ds_base" class="com.alibaba.druid.pool.DruidDataSource">
		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="5" />
		<property name="minIdle" value="20" />
		<property name="maxActive" value="100" />
		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000" />
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="validationQuery" value="SELECT 0" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
		<!-- 对于长时间不使用的连接强制关闭 -->
		<property name="removeAbandoned" value="true" />
		<property name="removeAbandonedTimeout" value="120" />
		<!-- 配置监控统计拦截的filters -->
		<property name="filters" value="stat" />
	</bean>
	<bean id="ds_sso" parent="ds_base" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/SSO?useUnicode=true&amp;characterEncoding=UTF8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	<bean id="ds_api" parent="ds_base" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<!-- 基本属性 url、user、password -->
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/API?useUnicode=true&amp;characterEncoding=UTF8" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
    <bean id="ds" class="org.anyline.config.db.ds.DynamicDataSource">  
	    <property name="targetDataSources">  
	        <map key-type="java.lang.String">
	            <!-- 指定lookupKey和与之对应的数据源 -->
	            <entry key="ds_sso" value-ref="ds_sso"></entry>  
	            <entry key="ds_api" value-ref="ds_api"></entry>  
	        </map>  
	    </property>  
	    <!-- 这里可以指定默认的数据源 -->
	    <property name="defaultTargetDataSource" ref="ds_sso" />  
	</bean>
	<!-- JDBC模板 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="ds" />
	</bean>
JAVA中三种方式调用


1.DataSourceHolder.setDataSource(String dataSource, boolean auto)

dataSource:对应配置文件中<entry key="ds_sso" value-ref="ds_sso"></entry>的key

auto:执行一次SQL后,是否自动还原为本次setDataSource执行之前的数据源

2.在AnylineService.query等方法指定数据源

service.query("<ds_api>表名");

需要注意的是,通过这种方式指定数据源,仅对本次操作有效,执行完本次操作后,数据源还原为上次设置的数据源

3.通过注解或拦截器执行DataSourceHolder.setDataSource



最近更新 搜索 提交