spring boot多数据源下的事务配置

1、启动项目排除自动注入数据源

   

@SpringBootApplication(exclude = { DruidDataSourceAutoConfigure.class})

2、配置数据源中添加事务配置

  

@Bean(name = "mysqlV2Tx")
public DataSourceTransactionManager transactionManager(@Qualifier("mysqlV2DataSource") DataSource dataSource) {
      return new DataSourceTransactionManager(dataSource);
}
package com.fun.cim.con.config;


@Configuration
@MapperScan(basePackages = { "com.fun.cim.con.mapper.v2"}, sqlSessionFactoryRef = "mysqlV2SqlSessionFactory")
public class MySqlV2DruidConfig {

	private static final Logger LOGGER = LoggerFactory.getLogger(MySqlV2DruidConfig.class);

	@Value("${spring.datasource.v2.url}")
	private String dbUrl;

	@Value("${spring.datasource.v2.username}")
	private String username;

	@Value("${spring.datasource.v2.password}")
	private String password;

	@Value("${spring.datasource.v2.driver-class-name}")
	private String driverClassName;

	@Value("${spring.datasource.initialSize}")
	private int initialSize;

	@Value("${spring.datasource.minIdle}")
	private int minIdle;

	@Value("${spring.datasource.maxActive}")
	private int maxActive;

	@Value("${spring.datasource.maxWait}")
	private int maxWait;

	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;

	@Value("${spring.datasource.minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;

	@Value("${spring.datasource.validationQuery}")
	private String validationQuery;

	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;

	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;

	@Value("${spring.datasource.poolPreparedStatements}")
	private boolean poolPreparedStatements;

	@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;

	@Value("${spring.datasource.v2.filters}")
	private String filters;

	@Value("{spring.datasource.connectionProperties}")
	private String connectionProperties;

	@Bean(name = "mysqlV2DataSource")
	public DataSource mysqlV2DataSource() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl(dbUrl);
		datasource.setUsername(username);
		datasource.setPassword(password);
		datasource.setDriverClassName(driverClassName);
		datasource.setInitialSize(initialSize);
		datasource.setMinIdle(minIdle);
		datasource.setMaxActive(maxActive);
		datasource.setMaxWait(maxWait);
		datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		datasource.setValidationQuery(validationQuery);
		datasource.setTestWhileIdle(testWhileIdle);
		datasource.setTestOnBorrow(testOnBorrow);
		datasource.setTestOnReturn(testOnReturn);
		datasource.setPoolPreparedStatements(poolPreparedStatements);
		datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
		datasource.setConnectionProperties(connectionProperties);
		return datasource;
	}

	@Bean(name = "mysqlV2SqlSessionFactory")
	public SqlSessionFactory mysqlV2SqlSessionFactory(@Qualifier("mysqlV2DataSource") DataSource dataSource) {
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			List mapperLocations = new ArrayList();
			mapperLocations.addAll(Arrays.asList(resolver.getResources("classpath:mybatis/mapper/v2/*.xml")));
			
			bean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
			bean.setMapperLocations(mapperLocations.toArray(new Resource[0]));
			// 手动设置session工厂时,需要手动添加分页插件
			List plugins = new ArrayList();
			plugins.add(paginationInterceptor());
			bean.setPlugins(plugins.toArray(new Interceptor[0]));
			return bean.getObject();
		} catch (Exception e) {
			LOGGER.error(MessageFormat.format("构建mysql SessionFactory 出错 :{0}", e.getMessage()));
			throw new RuntimeException(e);
		}
	}

	@Bean
	public SqlSessionTemplate mysqlV2SqlSessionTemplate(@Qualifier("mysqlV2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		// 使用上面配置的Factory
		SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
		return template;
	}

    //事务配置
	@Bean(name = "mysqlV2Tx")
	public DataSourceTransactionManager transactionManager(@Qualifier("mysqlV2DataSource") DataSource dataSource) {
			return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "mysqlV2DruidServlet")
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		// 设置登录查看信息的账号密码.
		servletRegistrationBean.addInitParameter("loginUsername", "admin1");
		servletRegistrationBean.addInitParameter("loginPassword", "admin1");
		return servletRegistrationBean;
	}

	@Bean(name = "mysqlV2filterRegistrationBean")
	public FilterRegistrationBean filterRegistrationBean() {
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}

	/**
	* 分页插件mybatis-plus配置使用
	 */
	@Bean
	public PaginationInterceptor paginationInterceptor() {
		return new PaginationInterceptor();
	}

}

3、添加@transactional注解

@Transactional(value = "mysqlV2Tx",rollbackFor = Exception.class)

以上方法仅适用于多数据源单独使用。多数据源混合使用需要采用分布式事务

你可能感兴趣的:(spring,cloud)