DynamicDataSource.java 1.21 KB
package com.huaheng.framework.datasource;

import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源
 *
 * @author huaheng
 */
public class DynamicDataSource extends AbstractRoutingDataSource
{
    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
    {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    public DynamicDataSource(){

    }

    @Override
    protected Object determineCurrentLookupKey()
    {
        Object lookupKey = contextHolder.get();
        return lookupKey;
    }

    public static void master(){
        contextHolder.set(DatabaseType.Master);
    }

    public static void slave() {
        contextHolder.set(DatabaseType.Slave);
    }

    public static void clear() {
        contextHolder.remove();
    }

    public static DatabaseType getType() {
        return contextHolder.get();
    }

    public enum DatabaseType {
        Master, Slave
    }
}