use of com.ctrip.xpipe.redis.core.protocal.protocal.ArrayParser in project x-pipe by ctripcorp.
the class RoleCommandHandlerTest method test.
@Test
public void test() {
final AtomicReference<ByteBuf> result = new AtomicReference<>();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
result.set((ByteBuf) invocation.getArguments()[0]);
return null;
}
}).when(redisClient).sendMessage(any(ByteBuf.class));
handler.doHandle(new String[0], redisClient);
sleep(10);
String real = ByteBufUtils.readToString(result.get());
String expected = String.format("*5\r\n+%s\r\n+%s\r\n:%d\r\n+%s\r\n:%d\r\n", SERVER_ROLE.KEEPER.toString(), host, port, masterState.getDesc(), masterOffset);
Assert.assertEquals(expected, real);
// reverse
Object[] reverse = new ArrayParser().read(Unpooled.wrappedBuffer(real.getBytes())).getPayload();
SlaveRole slaveRole = new SlaveRole(reverse);
Assert.assertEquals(SERVER_ROLE.KEEPER, slaveRole.getServerRole());
Assert.assertEquals(host, slaveRole.getMasterHost());
Assert.assertEquals(port, slaveRole.getMasterPort());
Assert.assertEquals(masterState, slaveRole.getMasterState());
Assert.assertEquals(masterOffset, slaveRole.getMasterOffset());
}
use of com.ctrip.xpipe.redis.core.protocal.protocal.ArrayParser in project x-pipe by ctripcorp.
the class DefaultRedisClient method readCommands.
@Override
public String[] readCommands(ByteBuf byteBuf) {
while (true) {
switch(commandState) {
case READ_SIGN:
if (!hasDataRead(byteBuf)) {
return null;
}
int readIndex = byteBuf.readerIndex();
byte sign = byteBuf.getByte(readIndex);
if (sign == RedisClientProtocol.ASTERISK_BYTE) {
redisClientProtocol = new ArrayParser();
} else if (sign == '\n') {
byteBuf.readByte();
return new String[] { "\n" };
} else {
redisClientProtocol = new SimpleStringParser();
}
commandState = COMMAND_STATE.READ_COMMANDS;
case READ_COMMANDS:
RedisClientProtocol<?> resultParser = redisClientProtocol.read(byteBuf);
if (resultParser == null) {
return null;
}
Object result = resultParser.getPayload();
if (result == null) {
return new String[0];
}
commandState = COMMAND_STATE.READ_SIGN;
String[] ret = null;
if (result instanceof String) {
ret = handleString((String) result);
} else if (result instanceof Object[]) {
ret = handleArray((Object[]) result);
} else {
throw new IllegalStateException("unkonw result array:" + result);
}
return ret;
default:
throw new IllegalStateException("unkonwn state:" + commandState);
}
}
}
Aggregations