數據庫主從搭建及應用數據源切換

數據庫主從架構過程,參考https://www.cnblogs.com/cloudhere/p/10991520.html

java關於主從的應用在這裏寫一下:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
      <version>2.2.2.RELEASE</version>
    </dependency>
@Aspect
@Component
@Order(1)
public class DataSourceAop {

    //公共參數,創建時間
    private static final String CREATE_DATE = "createDate";
    //修改時間
    private static final String UPDATE_DATE = "updateDate";

    /**
     * 只讀方法的設置
     */
    @Pointcut("execution(* com.haozi.miaoshaproject.service.impl..*.select*(..))"
            + "|| execution(* com.haozi.miaoshaproject.service.impl..*.find*(..))"
            + "|| execution(* com.haozi.miaoshaproject.service.impl..*.get*(..))")
    public void readonlyPointcut(){

    }

    /**
     * 讀寫方法的設置
     */
    @Pointcut("execution(* com.haozi.miaoshaproject.service.impl..*.save*(..))"
            + "|| execution(* com.haozi.miaoshaproject.service.impl..*.update*(..))"
            + "|| execution(* com.haozi.miaoshaproject.service.impl..*.insert*(..))"
            + "|| execution(* com.haozi.miaoshaproject.service.impl..*.add*(..))")
    public void writePointcut(){

    }

    /**
     * 具體切入
     * @param joinPoint
     */
    @Before("writePointcut()")
    public void setDataBaseMaster(JoinPoint joinPoint) {
        DynamicDataSource.setDataBaseType(DynamicDataSource.DatabaseType.primaryDataSource);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Object[] args = joinPoint.getArgs();

        if (args != null && args.length > 0) {
            Object argument = args[0];
            BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
            System.out.println("----------主庫------" + signature.getMethod().getName());
            //新增時設置創建時間
            if(signature.getMethod().getName().contains("add")
                    || signature.getMethod().getName().contains("save")
                    || signature.getMethod().getName().contains("insert")){
                // 設置創建時間和修改時間
                if (beanWrapper.isWritableProperty(CREATE_DATE)) {
                    beanWrapper.setPropertyValue(CREATE_DATE, new Date());
                }
            }
            //修改時間設置
            if (beanWrapper.isWritableProperty(UPDATE_DATE)) {
                beanWrapper.setPropertyValue(UPDATE_DATE, new Date());
            }
        }
    }

    /**
     * 具體切入
     * @param joinPoint
     */
    @Before("readonlyPointcut()")
    public void setDataBaseSlave(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        DynamicDataSource.setDataBaseType(DynamicDataSource.DatabaseType.readonlyDataSource);
        System.out.println("----------從庫------" + signature.getMethod().getName());
    }
}
@Configuration
public class DruidConfig {
    @Primary
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.master")
    public DataSource druidPrimary(){
        return new DruidDataSource();
    }

    @Bean(name = "readonlyDataSource")
    @Qualifier("readonlyDataSource")
    @ConfigurationProperties(prefix="spring.datasource.slave")
    public DataSource druidReadonly(){
        return new DruidDataSource();
    }

    /**
     * 配置Druid的監控
     * 1.配置一個管理後臺的Servlet,對數據庫進行可視化管理
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean =new ServletRegistrationBean(new StatViewServlet() , "/druid/*");
        Map<String,String> initParams=new HashMap<>();
        initParams.put("loginUsername", "root");
        initParams.put("loginPassword", "admin");
        initParams.put("allow", "");//默認就是允許所有訪問。
        //initParams.put("deny","");
        //拒絕訪問的ip
        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 2.配置一個監控的filter
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean =new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> initParams=new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        //攔截所有請求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;

    }
}
public class DynamicDataSource extends AbstractRoutingDataSource {
    /**
     * 列出所有的數據源key(常用數據庫名稱來命名)
     * 注意:
     * 1)這裏數據源與數據庫是一對一的
     */
    public enum DatabaseType {
        //主庫
        primaryDataSource,
        //從庫
        readonlyDataSource
    }

    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();

    public static void setDataBaseType(DatabaseType type){
        contextHolder.set(type);
    }

    public static DatabaseType getDataBaseType(){
        DatabaseType db = contextHolder.get();
        if (db == null)
            db = DatabaseType.primaryDataSource;
        return db;
    }

    public Object determineCurrentLookupKey() {
        return getDataBaseType();
    }

    /**
     * 清理鏈接類型
     */
    public static void clearDbType() {
        contextHolder.remove();
    }
}
@Configuration
@MapperScan(value = "com.haozi.miaoshaproject.dao")//,sqlSessionTemplateRef = "sqlSessionTemplatePrimary"
public class MybatisConfig {

    /**
     * @Primary 該註解表示在同一個接口有多個實現類可以注入的時候,默認選擇哪一個,而不是讓@autowire註解報錯
     * @Qualifier 根據名稱進行注入,通常是在具有相同的多個類型的實例的一個注入(例如有多個DataSource類型的實例)
     */
    @Bean
    public DynamicDataSource dataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
                                        @Qualifier("readonlyDataSource") DataSource readonlyDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DynamicDataSource.DatabaseType.primaryDataSource, primaryDataSource);
        targetDataSources.put(DynamicDataSource.DatabaseType.readonlyDataSource, readonlyDataSource);

        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 該方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(primaryDataSource);// 默認的datasource設置爲myTestDbDataSource

        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //配置xml目錄
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath*:mapping/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置事務管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }
}

主要思想就是使用切面監控實現類方法,不同的方法切換不同的數據源。

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