com.alibaba.dts.client.route.impl.RoundRobinRule Maven / Gradle / Ivy
package com.alibaba.dts.client.route.impl;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import com.alibaba.dts.client.executor.job.context.JobContext;
import com.alibaba.dts.client.route.RouteRule;
import com.alibaba.dts.common.domain.remoting.RemoteMachine;
/**
* 轮训路由规则
*
* @author Ronan Zhan
*/
public class RoundRobinRule implements RouteRule {
//计数器
// private AtomicLong counter = new AtomicLong(0L);
private static final ConcurrentHashMap counters = new ConcurrentHashMap();
@Override
public RemoteMachine rule(JobContext jobContext,
List machines) {
if (null == machines || machines.isEmpty()) {
return null;
}
//生成下标
String jobProcessor = jobContext.getJob().getJobProcessor().trim();
AtomicLong counter = counters.get(jobProcessor);
if (counter == null) {
counter = new AtomicLong();
AtomicLong counterExisted = counters.putIfAbsent(jobProcessor, counter);
if (counterExisted != null) {
counter = counterExisted;
}
}
int index = (int) (counter.get() % machines.size());
//计数器递增
counter.incrementAndGet();
return machines.get(Math.abs(index));
}
}