美文网首页我爱编程
Spring boot+Mybatis多数据源动态切换

Spring boot+Mybatis多数据源动态切换

作者: 离别刀 | 来源:发表于2018-05-25 13:35 被阅读0次

通过重写AbstractRoutingDataSource类中方法determineTargetDataSource,determineCurrentLookupKey,afterPropertiesSet实现动态DataSource。
determineTargetDataSource:获取动态DataSource
determineCurrentLookupKey:获取动态数据源名称
afterPropertiesSet:重写该方法,防止调用父类方法,自己管理多数据源

本例适用场景:多租户SAAS系统,基于数据库schema或者数据库实例完全隔离的系统。系统中有一个master数据库,会配置其他各个租户数据源的连接信息,这个是由系统配置统一维护。任何request请求都会标记该租户信息,然后由后台拦截初始化ThreadLocal变量。DynamicDataSource中根据ThreadLocal切换不同的数据源。

数据源标记ThreadLocal

public class DynamicDataSourceHolder {
     private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
        public static void setDataSource(String dataSource) {  
            contextHolder.set(dataSource);  
        }  
        public static String getDataSource() {  
            return contextHolder.get();  
        }  
        public static void clearDataSource() {  
            contextHolder.remove();  
        }  
}

@Component
public class SpringBeanHelper implements ApplicationContextAware {
    private static ApplicationContext context;
    public static <T> T getBean(Class<T> requiredClass) {
        return context.getBean(requiredClass);
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context= applicationContext;
    }
}

拦截请求设置ThreadLocal

@Configuration
public class DBInterceptor implements HandlerInterceptor{
    private static final Logger logger= LoggerFactory.getLogger(DBInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        //这里只是简单从请求参数中获取,真实场景可能会从header中租户id或者域名区分
        String db= request.getParameter("db");
        if(StringUtils.isNoneEmpty(db)) {
            logger.info("db is: {}",db);
            DynamicDataSourceHolder.setDataSource(db);
            return true;
        }
        logger.error("db is empty");
        response.getWriter().print("no authority.");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        DynamicDataSourceHolder.clearDataSource();
        logger.info("clear db holder.");
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {}
}

动态数据源实现

@Configuration
public class DynamicDataSource extends AbstractRoutingDataSource{
    private static final Logger logger= LoggerFactory.getLogger(DynamicDataSource.class);
    
    @Value("${jdbc.master.database}")
    private String masterDataBase;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //保存动态创建的数据源
    private static final Map<String,DataSource> targetDataSource = new HashMap<>();

    //主数据库初始化
    @PostConstruct
    private void init() {
        DataSource dataSource= (DataSource) DataSourceBuilder.create(Thread.currentThread().getContextClassLoader())
                .driverClassName(driver)
                .url(url)
                .username(username)
                .password(password).build();
        dataSource.setMaxActive(1000);
        dataSource.setMaxIdle(200);
        dataSource.setMinIdle(200);
        dataSource.setMaxWait(10000);
        putDataSource(masterDataBase, dataSource);
    }
    
    @Override
    protected DataSource determineTargetDataSource() {
        // 根据数据库选择方案,拿到要访问的数据库
        String dataSourceName = determineCurrentLookupKey();
        // 根据数据库名字,从已创建的数据库中获取要访问的数据库
        DataSource dataSource = targetDataSource.get(dataSourceName);
        if(null == dataSource) {
            //从已创建的数据库中获取要访问的数据库,如果没有则创建一个
            dataSource = this.selectDataSource(dataSourceName);
        }
        return dataSource;
    }

    @Override
    protected String determineCurrentLookupKey() {
        String dataSourceName = DynamicDataSourceHolder.getDataSource();
        return dataSourceName;
    }
    
    /**
     * 该方法为同步方法,防止并发创建两个相同的数据库
     * @param dbname
     * @return
     */
    private synchronized DataSource selectDataSource(String dbname) {
        // 双重检查
        DataSource obj = this.targetDataSource.get(dbname);
        if (null != obj) {
            return obj;
        } 
        // 为空则创建数据库
       DataSource dataSource = this.setDataSource(dbname);
        if (null != dataSource) {
            // 将新创建的数据库保存到map中
            putDataSource(dbname, dataSource);
            return dataSource;
        }
        throw new RuntimeException("创建数据源失败!");
    }
    
    private void putDataSource(String dbname, DataSource dataSource) {
        this.targetDataSource.put(dbname, dataSource);
    }
    
    /**
     * 查询对应数据库的信息
     * @param dbname
     * @return
     */
    private DataSource setDataSource(String dbname) {
        String oriSource = DynamicDataSourceHolder.getDataSource();
        // 先切换回主库
        DynamicDataSourceHolder.setDataSource(masterDataBase);
        // 查询所需信息
        CenterDatabase database = getDataBaseService().getById(dbname);
        if(database==null){
            throw new RuntimeException("获取目标数据库连接信息失败。");
        }
        // 切换回目标库
        DynamicDataSourceHolder.setDataSource(oriSource);
        DataSource dataSource = (DataSource)DataSourceBuilder.create(Thread.currentThread().getContextClassLoader())
                .driverClassName(database.driver)                
                .url(database.parseMysqlURL())                
                .username(database.username)
                .password(database.password).build();
        dataSource.setMaxActive(3000);
        dataSource.setMaxIdle(6);
        dataSource.setMaxWait(5000);
        return dataSource;
    }
    
    @Override
    public void afterPropertiesSet() {
        //do nothing just for override. becauseof targetDataSource management by self.
    }
    
    private DatabaseService getDataBaseService(){
        return SpringBeanHelper.getBean(DatabaseService.class);
    }

}

Mybatis配置

@Configuration
public class MybatisConfig implements TransactionManagementConfigurer {
    //mybatis 配置路径
    private static String MYBATIS_CONFIG = "mybatis-config.xml";    
    //mybatis mapper resource 路径
    private static String MAPPER_PATH = "/mapper/**.xml";
    private String typeAliasPackage = "com.test.mapper";   
    
    @Autowired
    private DynamicDataSource dataSource;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
         return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
        //添加mapper 扫描路径       
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();        
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;
        bean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        //设置datasource     
        bean.setDataSource(dataSource);   
        //设置typeAlias 包扫描路径  
        bean.setTypeAliasesPackage(typeAliasPackage);
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

说明:以上方案在使用多实例数据库的时候问题不大。但如果考虑使用单实例数据库,多schema的方案需要注意的各个租户数据库连接问题,防止有的租户占用大量连接,浪费资源。

相关文章

网友评论

    本文标题:Spring boot+Mybatis多数据源动态切换

    本文链接:https://www.haomeiwen.com/subject/gowyjftx.html