spring boot微服務架構mybatis多數據源切換

1,先看個目錄結構圖


可以看到,我把要設置的配置文件都放在了config文件夾下面

2,Application.java是程序啓動項,裏面必須設置

3,application.properties是多數據源切換的配置文件

好,接下來開始進行多數據源的切換!!!

一、先看看application.properties文件吧,配置多數據源:dbType用的超高可用的com.zaxxer.hikari.HikariDataSource,這裏比較關鍵

#springboot\u5355\u636E\u6E90\u914D\u7F6E
spring.datasource.url=jdbc:mysql://localhost:3306/fcoc-schedule?useUnicode=true&useSSL=false&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dbType=MYSQL
spring.datasource.validateQuery=select 1

customer.datasource.names=db1,db2,db3
#springboot\u591A\u6570\u636E\u6E90\u914D\u7F6E
#\u6570\u636E\u6E901
customer.datasource.db1.url=jdbc:sqlserver://123.6.21.123:2433;databaseName=ecology8
customer.datasource.db1.username=spbcd
customer.datasource.db1.password=spb116688
customer.datasource.db1.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
customer.datasource.db1.dbType=com.zaxxer.hikari.HikariDataSource
customer.datasource.db1.max-idle=10
customer.datasource.db1.max-wait=10000
customer.datasource.db1.min-idle=5
customer.datasource.db1.initial-size=5

#\u6570\u636E\u6E902  
customer.datasource.db2.url=jdbc:mysql://localhost:3306/fcoc-control?useUnicode=true&useSSL=false&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true
customer.datasource.db2.username=root
customer.datasource.db2.password=123456
customer.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
customer.datasource.db2.dbType=com.zaxxer.hikari.HikariDataSource
customer.datasource.db2.max-idle=10
customer.datasource.db2.max-wait=10000
customer.datasource.db2.min-idle=5
customer.datasource.db2.initial-size=5

customer.datasource.db3.url = jdbc:mysql://123.105.123.123:3306/iretail-web?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false
customer.datasource.db3.username = root
customer.datasource.db3.password = 123456
customer.datasource.db3.driver-class-name = com.mysql.jdbc.Driver
customer.datasource.db3.dbType=com.zaxxer.hikari.HikariDataSource
customer.datasource.db3.max-idle=10
customer.datasource.db3.max-wait=10000
customer.datasource.db3.min-idle=5
customer.datasource.db3.initial-size=5

#mybatis
mybatis.mapper-locations=classpath*:repo/*.xml
mybatis.type-aliases-package=com.dhc.fcoc


在applicationContext-dao.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
		default-lazy-init="true">

	<bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	    <property name="properties">
	        <props>
	            <prop key="SQLServer">sqlserver</prop>
	           <!--  <prop key="DB2">db2</prop>
	            <prop key="Oracle">oracle</prop>
	            <prop key="MySQL">mysql</prop> -->
	        </props>
	    </property>
	</bean>
	
	<bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider">
	    <property name="properties" ref="vendorProperties"/>
	</bean>
	
	<!-- MyBatis配置 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:conf/mybatis/mybatis-config.xml"/>
		<!-- 自動掃描domain目錄, 省掉mybatis-config.xml裏的手工配置  -->
		<property name="typeAliasesPackage" value="com.dhc.**.domain" />
		<!-- 顯式指定Mapper文件位置 -->
		<property name="mapperLocations" value="classpath*:com/dhc/**/repo/*Mapper.xml" />
		<!-- <property name="mapperLocations" value="classpath:conf/mybatis/*Mapper.xml" /> -->
		<property name="databaseIdProvider" ref="databaseIdProvider"/>
	</bean>
	

	<bean class="com.dhc.ilead.pa.spring.MapperScannerConfigurer">
		<property name="basePackage" value="com.dhc.**.repo" />
		<!-- 支持過濾由marker interface和annotation指定的mapper。
			annotation屬性定義了供搜索的annotation。marker interface屬性定義了供搜索的父接口。
			若以上兩個屬性均定義,則匹配其中任何一個標準的mapper均包含其中。
			默認情況下,兩個屬性均爲null,則指定base package下的所有interface均被加載爲mapper。 
		-->
		<property name="markerInterface" value="com.dhc.ilead.base.repo.BaseRepository" />
		<property name="annotationClass" value="com.dhc.ilead.base.repo.ILeadRepo"/>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
		<property name="properties">
			<props>
				<prop key="notEmpty">TRUE</prop>
			</props>
		</property>
	</bean>
	
	<!-- druid連接池配置 begin -->
	<bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource" abstract="true">
		
		<!-- 配置獲取連接等待超時的時間 -->
	    <property name="maxWait" value="60000" />
	
		<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 -->
	    <property name="timeBetweenEvictionRunsMillis" value="60000" />
	
		 <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
	    <property name="minEvictableIdleTimeMillis" value="300000" />
	
	    <property name="validationQuery" value="${spring.datasource.validateQuery}" />
	    <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" />
	
		 <!-- 配置監控統計攔截的filters -->
	    <property name="filters" value="slf4j" />
		<property name="proxyFilters">
		    <list>
		        <ref bean="stat-filter" />
		    </list>
		</property>    
	</bean>

	<bean id="nativeDataSource" parent="parentDataSource" init-method="init" destroy-method="close">
		<!--  基本屬性 url,user,password -->
		<property name="driverClassName" value="${spring.datasource.driver-class-name}" />
	    <property name="url" value="${spring.datasource.url}" />
	    <property name="username" value="${spring.datasource.username}" />
	    <property name="password" value="${spring.datasource.password}" />
	
		<!-- 配置初始化大小,最小,最大 -->
	    <property name="initialSize" value="10" />
	    <property name="minIdle" value="5" /> 
	    <property name="maxActive" value="50" />
	   
	</bean>

	<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
	    <property name="slowSqlMillis" value="3000" />
	    <property name="logSlowSql" value="true" />
	</bean>	
	
	<bean id="dataSource" class="org.ilead.base.dao.ds.ILeadDataSource">
		<property name="nativeDataSource" ><ref bean="nativeDataSource"/>
		</property>
		<property name="databaseType" value="${spring.datasource.dbType}" />
	</bean>
	<!-- druid連接池配置 end -->
	
	<!-- 單數據源事務 -->
	<!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
		<property name="dataSource" ref="dataSource" /> </bean> -->

	<!-- 使用annotation定義事務 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="0"/>
	
	<!-- 使用aop定義事務 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" />
			<tx:method name="find*" read-only="true" />
			<!-- add at 20150514 begin -->
			<tx:method name="query*" read-only="true" />
			<tx:method name="count*" read-only="true" />
			<tx:method name="list*" read-only="true" />
			<tx:method name="select*" read-only="true" />
			<!-- add at 20150514 end -->
			<tx:method name="exclusive__*" propagation="REQUIRES_NEW"
				rollback-for="Exception" />
			<tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
		</tx:attributes>
	</tx:advice>

<!-- 	<aop:config>
		<aop:pointcut id="txPointcut"
			expression="execution(* *..as*..*(..)) or (execution(* *..api*..*(..)) and !execution(* com.dhc.ilead.base.api.*..*(..)))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" order="1" />
	</aop:config> -->

</beans>


二、DynamicDataSourceRegister動態註冊數據源的類,貼代碼,仔細看裏面的有些要根據自己項目來設置的項!別頭鐵去一頓瞎複製!!裏面會有報錯的,是因爲所需要的其他類在下面要繼續創建!!!別

package com.dhc.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

/**
 * 
 * @FileName DynamicDataSourceRegister.java
 * @Author 肖高翔
 * @At 2018年6月16日 上午10:08:31
 * @Desc 動態數據源註冊,啓動動態數據源請在啓動類中(Application.java中添加 @Import(DynamicDataSourceRegister.class))
 * 
 */
@Configuration
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {

	private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);

	private ConversionService conversionService = new DefaultConversionService();
	private PropertyValues dataSourcePropertyValues;

	// 如配置文件中未指定數據源類型,使用該默認值
	private static final Object DATASOURCE_TYPE_DEFAULT = "com.zaxxer.hikari.HikariDataSource";

	// 數據源
	private DataSource defaultDataSource;
	private Map<String, DataSource> customDataSources = new HashMap<>();

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
		// 將主數據源添加到更多數據源中
		targetDataSources.put("dataSource", defaultDataSource);
		DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
		// 添加更多數據源
		targetDataSources.putAll(customDataSources);
		for (String key : customDataSources.keySet()) {
			DynamicDataSourceContextHolder.dataSourceIds.add(key);
		}

		// 創建DynamicDataSource
		GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
		beanDefinition.setBeanClass(DynamicDataSource.class);
		beanDefinition.setSynthetic(true);
		MutablePropertyValues mpv = beanDefinition.getPropertyValues();
		mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
		mpv.addPropertyValue("targetDataSources", targetDataSources);
		registry.registerBeanDefinition("dataSource", beanDefinition);

		logger.info("Dynamic DataSource Registry");
	}

	/**
	 * 加載多數據源配置
	 */
	@Override
	public void setEnvironment(Environment env) {
		initDefaultDataSource(env);
		initCustomDataSources(env);
	}

	/**
	 * 初始化主數據源
	 * 
	 * @Title initDefaultDataSource
	 * @Author 肖高翔
	 * @param env
	 *            void
	 */
	private void initDefaultDataSource(Environment env) {
		// 讀取主數據源(默認數據源)
		RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
		Map<String, Object> dsMap = new HashMap<>();
		dsMap.put("type", null);
		dsMap.put("driver-class-name", propertyResolver.getProperty("driver-class-name"));
		dsMap.put("url", propertyResolver.getProperty("url"));
		dsMap.put("username", propertyResolver.getProperty("username"));
		dsMap.put("password", propertyResolver.getProperty("password"));

		// 創建(註冊)數據源
		defaultDataSource = buildDataSource(dsMap);

		dataBinder(defaultDataSource, env);
	}

	/**
	 * 
	 * 創建DataSource
	 *
	 * @Title buildDataSource
	 * @Author 肖高翔
	 * @param dsMap
	 *            數據源的map
	 * @param type
	 *            數據源的類型,這裏用了超高效的:com.zaxxer.hikari.HikariDataSource
	 * @param driverClassName
	 *            註冊驅動名
	 * @param url
	 *            連接數據庫url
	 * @param username
	 *            連接數據庫用戶名
	 * @param password
	 *            連接數據庫密碼
	 * @return DataSource
	 */
	@SuppressWarnings("unchecked")
	public DataSource buildDataSource(Map<String, Object> dsMap) {
		try {
			Object type = dsMap.get("type");
			if (type == null)
				type = DATASOURCE_TYPE_DEFAULT;// 默認DataSource

			Class<? extends DataSource> dataSourceType;
			dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);

			String driverClassName = dsMap.get("driver-class-name").toString();
			String url = dsMap.get("url").toString();
			String username = dsMap.get("username").toString();
			String password = dsMap.get("password").toString();

			// 數據庫註冊對象
			DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username).password(password)
					.type(dataSourceType);

			// 創建數據庫
			return factory.build();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 爲DataSource綁定更多數據
	 * 
	 * @Title dataBinder
	 * @Author 肖高翔
	 * @param dataSource
	 *            數據源
	 * @param env
	 *            識別配置文件的類 void
	 */
	private void dataBinder(DataSource dataSource, Environment env) {
		RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
		dataBinder.setConversionService(conversionService);
		dataBinder.setIgnoreNestedProperties(false);
		dataBinder.setIgnoreInvalidFields(false);
		dataBinder.setIgnoreUnknownFields(true);
		// 將主數據源給清除,因爲最開始初始化時候已經將主數據源註冊了,將其他數據源添加進來
		if (dataSourcePropertyValues == null) {
			Map<String, Object> rpr = new RelaxedPropertyResolver(env, "spring.datasource").getSubProperties(".");
			Map<String, Object> values = new HashMap<>(rpr);
			// 排除已經設置的屬性
			values.remove("dbType");
			values.remove("driver-class-name");
			values.remove("url");
			values.remove("username");
			values.remove("password");
			dataSourcePropertyValues = new MutablePropertyValues(values);
		}
		dataBinder.bind(dataSourcePropertyValues);
	}

	/**
	 * 初始化更多數據源
	 * 
	 * @Title initCustomDataSources
	 * @Author 肖高翔
	 * @param env
	 *            void
	 */
	private void initCustomDataSources(Environment env) {
		// 讀取配置文件獲取更多數據源,也可以通過defaultDataSource讀取數據庫獲取更多數據源
		RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "customer.datasource.");
		// 這裏從application.properties配置文件裏面讀取names屬性
		String dsPrefixs = propertyResolver.getProperty("names");
		// 多個數據源
		for (String dsPrefix : dsPrefixs.split(",")) {
			Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
			DataSource ds = buildDataSource(dsMap);
			customDataSources.put(dsPrefix, ds);
			dataBinder(ds, env);
		}
	}

}


三、DynamicDataSource動態數據源,這個切換全靠AbstractRoutingDataSource

package com.dhc.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 
 * @FileName DynamicDataSource.java
 * @Author 肖高翔
 * @At 2018年6月15日 上午10:41:17
 * @Desc 動態數據源
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DynamicDataSourceContextHolder.getDataSourceType();
	}

}

四、DynamicDataSourceAspect  利用AOP切換數據源Advice

package com.dhc.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 
 * @FileName DynamicDataSourceAspect.java
 * @Author 肖高翔
 * @At 2018年6月15日 上午10:41:47
 * @Desc AOP切換數據源Advice
 */
@Aspect
@Order(-1) // 保證該AOP在@Transactional之前執行
@Component
public class DynamicDataSourceAspect {

	private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

	@Before("@annotation(ds)")
	public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
		String dsId = ds.name();
		if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
			System.out.println("數據源【{}】不存在,使用默認數據源 > {} " + ds.name() + " " + point.getSignature());
			logger.error("數據源[{}]不存在,使用默認數據源 > {}", ds.name(), point.getSignature());
		} else {
			System.out.println("Use DataSource : {} > {} " + ds.name() + " " + point.getSignature());
			logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
			DynamicDataSourceContextHolder.setDataSourceType(ds.name());
		}
	}

	@After("@annotation(ds)")
	public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
		System.out.println("Revert DataSource : {} > {} " + ds.name() + " " + point.getSignature());
		logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
		DynamicDataSourceContextHolder.clearDataSourceType();
	}

}

五、DynamicDataSourceContextHolder保存切換的數據源

package com.dhc.config;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @FileName DynamicDataSourceContextHolder.java
 * @Author 肖高翔
 * @At 2018年6月16日 上午10:06:30
 * @Desc 保存切換的數據源
 */
public class DynamicDataSourceContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
	public static List<String> dataSourceIds = new ArrayList<>();

	/**
	 * 設置數據源名
	 * 
	 * @Title setDataSourceType
	 * @Author 肖高翔
	 * @param dataSourceType
	 *            void
	 */
	public static void setDataSourceType(String dataSourceType) {
		System.out.println("切換到 { " + dataSourceType + " } 數據源");
		contextHolder.set(dataSourceType);
	}

	/**
	 * 獲取數據源名
	 * 
	 * @Title getDataSourceType
	 * @Author 肖高翔
	 * @return String
	 */
	public static String getDataSourceType() {
		return contextHolder.get();
	}

	/**
	 * 清除數據源名
	 * 
	 * @Title clearDataSourceType
	 * @Author 肖高翔 void
	 */
	public static void clearDataSourceType() {
		contextHolder.remove();
	}

	/**
	 * 判斷指定DataSrouce當前是否存在
	 * 
	 * @Title containsDataSource
	 * @Author 肖高翔
	 * @param dataSourceId
	 * @return boolean
	 */
	public static boolean containsDataSource(String dataSourceId) {
		return dataSourceIds.contains(dataSourceId);
	}
}

六、TargetDataSource在方法上使用該註解,用於指定使用哪個數據源,這是個註釋類,看清楚啊!

package com.dhc.config;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 
 * @FileName TargetDataSource.java
 * @Author 肖高翔
 * @At 2018年6月15日 上午10:44:41
 * @Desc 在方法上使用該註解,用於指定使用哪個數據源
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
	String name();
}

七、在Application.java啓動程序裏面添加@Import({ DynamicDataSourceRegister.class })

package com.dhc.fcoc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.CacheStatisticsAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.session.SessionAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

import com.dhc.config.DynamicDataSourceRegister;

@ImportResource(locations = { "classpath*:/conf/applicationContext.xml", "classpath*:/conf/applicationContext-legacy.xml" })
@Import({ DynamicDataSourceRegister.class })
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, SessionAutoConfiguration.class, RedisAutoConfiguration.class,
		RedisRepositoriesAutoConfiguration.class, CacheStatisticsAutoConfiguration.class, WebMvcAutoConfiguration.class })
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

我是在項目的AS層(也就是service,我這裏叫做AS層),方法頭部用了註解方式,然後就實現了數據源的動態切換

package com.dhc.fcoc.job.chl.employee.as;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Service;

import com.dhc.config.HttpClientUtils;
import com.dhc.config.TargetDataSource;
import com.dhc.fcoc.common.message.ResultCodeEnum;
import com.dhc.fcoc.job.chl.employee.domain.ChlHrmresource;
import com.dhc.fcoc.job.chl.employee.repo.ChlHrmresourceRepo;
import com.dhc.fcoc.main.param.common.ParamFieldConstant;
import com.dhc.ilead.base.exception.BaseASException;
import com.dhc.ilead.base.exception.BaseRepoException;
import com.dhc.ilead.base.service.BaseService;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;

@Service
public class ChlHrmresourceAS extends BaseService<ChlHrmresource, ChlHrmresourceRepo> {

	/**
	 * 查詢OA系統中的人員信息, 並同步到erp系統中
	 * 
	 * @Title batchInsert
	 * @Author 肖高翔
	 * @throws BaseASException
	 *             void
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	@TargetDataSource(name = "db1")  // 在這裏使用註解,這個名字就是application.properties裏面的names的數據源!自己根據項目自己定義
	public void batchInsert() throws BaseASException, ClientProtocolException, IOException {
		try {

			// 查詢人員信息
			List<ChlHrmresource> chlHrmresourceList = getDefaultRepository().selectAllHrmresource();

			// 封裝成json
			StringBuilder json = new StringBuilder();
			String strJson = JSONArray.fromObject(chlHrmresourceList).toString();

			// 這裏必須加上日期轉換的,否則查詢出來的日期會自動轉成long類型
			JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" }));
			json.append("{\"chlEmployeeDto\":");
			json.append(strJson);
			json.append("}");

			// 調用httpclient封裝好的方法即可
			HttpClientUtils.httpClientMethod(ParamFieldConstant.EMPLOYEE_URL, json.toString());
		} catch (BaseRepoException e) {
			throw new BaseASException(ResultCodeEnum.DB_ERROR.getCode(), ResultCodeEnum.DB_ERROR.getMessage() + "," + "異常類:" + this.getClass().getName() + ","
					+ "異常方法:" + Thread.currentThread().getStackTrace()[1].getMethodName(), e);
		}
	}
}

基本的pom.xml沒有貼,用常規的配置就可以。

在這過程中發現的問題是:

1,spring boot ,前後端分離,然後服務都在中臺服務中,如果直接在中臺服務裏面去設置這個多數據源切換,那麼通過web端訪問,他只能夠切換成一個數據源,後面的就沒用了。

2,可能的猜想是:在中臺這端,事務就已經開啓了。所以導致行不通。

3,當把切換數據源放在web端,放到事務未開始之前,就能夠隨意的進行切換,並且測試成功了。


有不明白spring boot中臺的可以私信我。我來給你們解釋一下這個概念。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章