DynamicDataSource.java 1.95 KB
package com.dili.titan.common.datasource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源.
 * @author zhoumin@360buy.com
 * 2011-9-13 下午6:12:18
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    private Map<String, DataSource> masterDataSources;
    private Map<String, DataSource> slaveDataSources;
    private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
    @PostConstruct
    public void setTargetDataSources() {
        Map<Object, Object> allDataSource = new HashMap<Object, Object>();
        if (masterDataSources != null) {
            allDataSource.putAll(masterDataSources);
        }
        if (masterDataSources != null) {
            allDataSource.putAll(slaveDataSources);
        }
        super.setTargetDataSources(allDataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String lookupKey = DataSourceSwitcher.getDataSource();
        if(StringUtils.isNotEmpty(lookupKey) && lookupKey.indexOf(DataSourceSwitcher.READ)>=0){
            lookupKey = DataSourceSwitcher.READ+(DataSourceSwitcher.RANDOM.nextInt(slaveDataSources.size()) + 1);
        }
        log.debug("获取数据源" + lookupKey);
        return lookupKey;
    }

    public Map<String, DataSource> getMasterDataSources() {
        return masterDataSources;
    }

    public void setMasterDataSources(Map<String, DataSource> masterDataSources) {
        this.masterDataSources = masterDataSources;
    }

    public Map<String, DataSource> getSlaveDataSources() {
        return slaveDataSources;
    }

    public void setSlaveDataSources(Map<String, DataSource> slaveDataSources) {
        this.slaveDataSources = slaveDataSources;
    }
}