package com.ssm.data;

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

import java.util.concurrent.atomic.AtomicInteger;


public class DynamicDataSource extends AbstractRoutingDataSource {
    private final int dataSourceNumber;
    private AtomicInteger count = new AtomicInteger(0);

    public DynamicDataSource(int dataSourceNumber) {
        this.dataSourceNumber = dataSourceNumber;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DynamicDataSourceHolder.getJdbcType();
        if (StringUtils.isNotBlank(typeKey) && DataSourceType.slave.getType().equals(typeKey)) {
            if (dataSourceNumber > 0) {
                // 读 简单负载均衡
                int number = count.getAndAdd(1);
                count.compareAndSet(1000000000,1);
                int lookupKey = number % dataSourceNumber;
                return lookupKey+"";
            }
        }
        return DataSourceType.master.getType();
    }
}
