/** * 提取获取全局序列操作通用流程 * * @param schema * @param seqName * @param count * @param operation * @return */ private long commonGetSeqVal( String schema, String seqName, Long count, FETCH_OPERATION operation) { long id = -1; // 节点路径 String idPath = String.format("%s/%s/%s", ROOT_PATH, schema, seqName); try { if (checkNodeExisted(idPath, client)) { client.sync(idPath, null); // 获取前,先从leader那里同步 !! 异步操作,但是有序 !! DistributedAtomicLong dal = buildDAL(idPath, true); switch (operation) { // 获取当前全局序列值 case CURR: AtomicValue<Long> currValue = dal.get(); if (currValue.succeeded()) { id = currValue.postValue(); } else { throw new AmoebaRuntimeException("fetch from id server error"); } break; // 获取下一个全局序列 case NEXT: AtomicValue<Long> nextValue = dal.increment(); if (nextValue.succeeded()) { id = nextValue.postValue(); } else { throw new AmoebaRuntimeException("fetch from id server error"); } break; // 批量获取全局序列 case BATCH: AtomicValue<Long> startValue = dal.get(); id = startValue.postValue() + count; if (startValue.succeeded()) { dal.forceSet(id); } break; default: throw new AmoebaRuntimeException("not support this fetch method"); } } else { throw new AmoebaRuntimeException(String.format("sequence %s is not existed", seqName)); } } catch (Exception e) { throw new AmoebaRuntimeException(e.getMessage()); } return id; }
/** 创建某个序列 */ @Override public synchronized SeqOperationResult createSeq( String schema, String seqName, long start, long offset) { SeqOperationResult result = null; // 节点路径 String idPath = String.format("%s/%s/%s", ROOT_PATH, schema, seqName); try { if (checkNodeExisted(idPath, client)) { result = new SeqOperationResult(false, String.format("sequence %s is existed", seqName)); } else { DistributedAtomicLong dal = buildDAL(idPath, false); dal.forceSet(start); result = new SeqOperationResult(true, ""); } } catch (Exception e) { throw new AmoebaRuntimeException(e.getMessage()); } return result; }