use of com.alipay.sofa.jraft.test.atomic.command.IncrementAndGetCommand in project sofa-jraft by sofastack.
the class AtomicClient method addAndGet.
public long addAndGet(PeerId peer, String key, long delta) throws InterruptedException {
try {
final IncrementAndGetCommand request = new IncrementAndGetCommand();
request.setKey(key);
request.setDetal(delta);
final Object response = this.rpcClient.invokeSync(peer.getEndpoint(), request, cliOptions.getRpcDefaultTimeout());
final BooleanCommand cmd = (BooleanCommand) response;
if (cmd.isSuccess()) {
return ((ValueCommand) cmd).getVlaue();
} else {
throw new IllegalStateException("Server error:" + cmd.getErrorMsg());
}
} catch (final Throwable t) {
throw new IllegalStateException("Remoting error:" + t.getMessage());
}
}
use of com.alipay.sofa.jraft.test.atomic.command.IncrementAndGetCommand in project sofa-jraft by sofastack.
the class AtomicStateMachine method onApply.
@Override
public void onApply(final Iterator iter) {
while (iter.hasNext()) {
final Closure done = iter.done();
CommandType cmdType;
final ByteBuffer data = iter.getData();
Object cmd = null;
LeaderTaskClosure closure = null;
if (done != null) {
closure = (LeaderTaskClosure) done;
cmdType = closure.getCmdType();
cmd = closure.getCmd();
} else {
final byte b = data.get();
final byte[] cmdBytes = new byte[data.remaining()];
data.get(cmdBytes);
cmdType = CommandType.parseByte(b);
switch(cmdType) {
case GET:
cmd = CommandCodec.decodeCommand(cmdBytes, GetCommand.class);
break;
case SET:
cmd = CommandCodec.decodeCommand(cmdBytes, SetCommand.class);
break;
case CAS:
cmd = CommandCodec.decodeCommand(cmdBytes, CompareAndSetCommand.class);
break;
case INC:
cmd = CommandCodec.decodeCommand(cmdBytes, IncrementAndGetCommand.class);
break;
}
}
final String key = ((BaseRequestCommand) cmd).getKey();
final AtomicLong counter = getCounter(key, true);
Object response = null;
switch(cmdType) {
case GET:
response = new ValueCommand(counter.get());
break;
case SET:
final SetCommand setCmd = (SetCommand) cmd;
counter.set(setCmd.getValue());
response = new BooleanCommand(true);
break;
case CAS:
final CompareAndSetCommand casCmd = (CompareAndSetCommand) cmd;
response = new BooleanCommand(counter.compareAndSet(casCmd.getExpect(), casCmd.getNewValue()));
break;
case INC:
final IncrementAndGetCommand incCmd = (IncrementAndGetCommand) cmd;
final long ret = counter.addAndGet(incCmd.getDetal());
response = new ValueCommand(ret);
break;
}
if (closure != null) {
closure.setResponse(response);
closure.run(Status.OK());
}
iter.next();
}
}
Aggregations