wzh1314wcq 2015-07-20 04:07
浏览 1482
已结题

声明式事务与mysql读写库配置问题

原来项目用的spring声明式事务处理 现在需要加上mysql的读写库 应用层使用的是aop切换数据库连接 但是读的时候有时候是读库 有时候是写库 不知道是否和声明式事务处理有关 各位大大帮忙看看

applicationContext.xml



<.....省略配置>



<.....省略配置>







<!-- write -->



<!-- read -->


























tx:attributes

<...省略...>



/tx:attributes
/tx:advice

aop:config








/aop:aspect
/aop:config

spring aop 动态选取

 @Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
public @interface DataSource {  
    String value();  
}  

多数据源

  public class ChooseDataSource extends AbstractRoutingDataSource {  

     @Override  
     protected Object determineCurrentLookupKey() {  
         return HandleDataSource.getDataSource();  
     }  

 } 

ThreadLocal

 public class HandleDataSource {  
    public static final ThreadLocal<String> holder = new ThreadLocal<String>();  
    public static void putDataSource(String datasource) {  
        holder.set(datasource);  
    }  

    public static String getDataSource() {  
        return holder.get();  
    }      
}  

切面类

 public class DataSourceAspect {     
    public void pointCut(){};    

     public void before(JoinPoint point)  
        {  
            Object target = point.getTarget();  
            System.out.println(target.toString());  
            String method = point.getSignature().getName();  
            System.out.println(method);  
            Class<?>[] classz = target.getClass().getInterfaces();  
            Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())  
                    .getMethod().getParameterTypes();  
            try {  
                Method m = classz[0].getMethod(method, parameterTypes);  
                System.out.println(m.getName());  
                if (m != null && m.isAnnotationPresent(DataSource.class)) {  
                    DataSource data = m.getAnnotation(DataSource.class);  
                    HandleDataSource.putDataSource(data.value());  
                }  

            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
}  

接着在service的接口类上

 @DataSource("read")
    public List<Page>findForIndex();

结果有时候是用read有时候用write 有没有人给点建议 谢谢了

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿