//给每个线程绑定
public static final ThreadLocal<String> holder = new ThreadLocal<>();
//写入对应的数据源key
private static final String MASTER="master";
private static final String SLAVE_1="slave_1";
private static final String SLAVE_2="slave_2";
private static AtomicInteger counter = new AtomicInteger(-1);
public static void setDataSource(DataSourceType dataSourceType){
if(dataSourceType==DataSourceType.MASTER){
holder.set(MASTER);
}else if(dataSourceType==DataSourceType.SLAVE){
holder.set(roundRobinSlaveKey());
}
}
DataSourceType 是一个枚举里面有MASTER和SLAVE;
考虑到并发的问题,我们这边是用ThreadLocal绑定线程,使它的值不会出现错误
表示使用注解要分配是主从sql,有两个slave,所以需要使它们合理分配
这边就使用的是简单的轮询算法,实际上就是取模,现在有2个slave数据库,所以模2
但是这里需要考虑到并发性的问题,不能使用integer,用到了原子类AtomicInteger;
AtimicInteger中的方法incrementAndGet先增加再获得,所以这边默认-1;
最后是为了防止counter 无限增长,所以就让它到一定的值的时候就恢复-1;
private static String roundRobinSlaveKey(){
//先获取再增加
Integer index = counter.incrementAndGet()%2;
if(counter.get()>9999){
counter.set(-1);
}
if(index == 0){
return SLAVE_1;
}else{
return SLAVE_2;
}
}