johnny2002 commented on issue #1720:
URL:
https://github.com/apache/shardingsphere-elasticjob/issues/1720#issuecomment-727561219
Here is my sample strategy :
```java
/**
* @author WeiZhou
*
* shardingTotalCount should be as same as JobInstances count.
* Neighbor 2 JobInstances backup eachother.
* Each partition will be assigned to same Jobinstance number or its backup.
* shardingTotalCount和jobInstances数量要一样.
* 相邻两个JobInstances互相备份.
* 每个作业分片要分配给相同号码的JobInstance或是它的备份单元
*/
@Slf4j
public class UnitizedAllocationJobShardingStrategy implements
JobShardingStrategy {
int[] backupMap = new int[] { 2, 1, 4, 3, 6, 5, 8, 7 };//Unit 1<>2,
3<>4, 5<>6, 7<>8 backup eachother
@Override
public Map<JobInstance, List<Integer>> sharding(final List<JobInstance>
jobInstances, final String jobName, final int shardingTotalCount) {
if (jobInstances.isEmpty()) {
return Collections.emptyMap();
}
JobInstance[] instArray = new JobInstance[shardingTotalCount];
for (JobInstance jobInst : jobInstances) {
//Job instance IDs like xxx@-@001, xxx@-@002, xxx@-@003 ...
String jobInstanceId = jobInst.getJobInstanceId();
jobInstanceId =
jobInstanceId.substring(jobInstanceId.indexOf(JobInstance.DELIMITER) +
JobInstance.DELIMITER.length());
int jobInstNum = Integer.parseInt(jobInstanceId);
instArray[jobInstNum - 1] = jobInst;
}
Map<JobInstance, List<Integer>> result = new
LinkedHashMap<>(jobInstances.size(), 1);
for (int i = 0; i < shardingTotalCount; i++) {
//looup same number JobInstance
JobInstance locatedJobInst = instArray[i];
log.debug("master of {} is {}", i, locatedJobInst);
if (locatedJobInst == null) {
//lookup backup JobInstance
if (backupMap[i] - 1 >= instArray.length ||
instArray[backupMap[i] - 1] == null) {
throw new RuntimeException("No main or backup job
executor found for unit:" + (i + 1) + ", backup unit:" + backupMap[i]);
}
locatedJobInst = instArray[backupMap[i] - 1];
log.debug("backup of {} is {}", i, locatedJobInst);
}
List<Integer> parts = result.get(locatedJobInst);
if (parts == null) {
parts = new ArrayList<>(2);
result.put(locatedJobInst, parts);
}
parts.add(i);
}
return result;
}
@Override
public String getType() {
return "UNIT_ALLOCATION";
}
}
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]