下面小编就为大家带来一篇解决spring mvc 多数据源切换,不支持事务控制的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
一个项目中需要使用两个数据库,Oracle 和Mysql,于是参考各个blog,实现此功能。写好后才发现,原来的事务失效了,我去…
spring-mybatis.xml 配置
classpath:spring/db.properties <!-- 配置数据源:MySQL start --> <!-- 初始化连接大小 --><!-- 连接池最大使用连接数量 --><!-- 连接池最小空闲 --><!-- 获取连接最大等待时间 --><!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --><!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --><!-- 打开removeAbandoned功能 --><!-- 1800秒,也就是30分钟 --><!-- 关闭abanded连接时输出错误日志 --><!-- 监控数据库 --> <map> </map><!-- oracle myBatis file --> <!-- --> <!-- configure transaction --> <!-- annotation transaction --><!-- interception transatcion --> <!-- 配置数据库注解aop --> <i style="color:transparent">来源gaodai$ma#com搞$代*码网</i><!--数据源选择切面,保证在事务开始之前执行-->
注解切换,默认使用oracle数据源
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD,ElementType.TYPE}) public @interface DataSource { String name() default DataSource.oracleDataSource; String mySqlDataSource = "mySqlDataSource"; String oracleDataSource = "oracleDataSource"; }
注解方式实现切换数据源,搜索注释,更换注释上面的数据源,支持类注释和方法注释
/** * Created by eastday on 2017/9/21. */ public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice { @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { MultipleDataSource.clearDataSource(); } @Override public void before(Method method, Object[] args, Object target) throws Throwable { //首先取类上的数据源 if(method.getDeclaringClass().isAnnotationPresent(DataSource.class) && !method.isAnnotationPresent(DataSource.class)) { DataSource datasource = method.getDeclaringClass().getAnnotation(DataSource.class); MultipleDataSource.setDataSource(datasource.name()); //方法上的数据源 优先级高于类上的 } else if (method.isAnnotationPresent(DataSource.class)) { DataSource datasource = method.getAnnotation(DataSource.class); MultipleDataSource.setDataSource(datasource.name()); } else { MultipleDataSource.setDataSource(DataSource.oracleDataSource); } } }
继承AbstractRoutingDataSource实现数据源切换
public class MultipleDataSource extends AbstractRoutingDataSource { private static final ThreadLocal dataSources = new InheritableThreadLocal(); public static void setDataSource(String dataSource) { dataSources.set(dataSource); } //清除数据源 public static void clearDataSource() { dataSources.remove(); } @Override protected Object determineCurrentLookupKey() { return dataSources.get(); } }
使用demo
@DataSource(name = DataSource.mySqlDataSource) public class ContentServiceImpl implements IContentService { @Autowired private IContentDao contentDao; @Override public Content queryOne(String type) { return contentDao.queryOne(type); } }
以上这篇解决spring mvc 多数据源切换,不支持事务控制的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持gaodaima搞代码网。
以上就是解决spring mvc 多数据源切换,不支持事务控制的问题的详细内容,更多请关注gaodaima搞代码网其它相关文章!