private Command newMergedCommand( final Map<Object, Command> mergeCommands, int mergeCount, final CommandCollector commandCollector, final CommandType commandType) { if (protocol == Protocol.Text) { String resultKey = (String) commandCollector.getResult(); byte[] keyBytes = ByteUtils.getBytes(resultKey); byte[] cmdBytes = commandType == CommandType.GET_ONE ? Constants.GET : Constants.GETS; final byte[] buf = new byte[cmdBytes.length + 3 + keyBytes.length]; ByteUtils.setArguments(buf, 0, cmdBytes, keyBytes); TextGetOneCommand cmd = new TextGetOneCommand(resultKey, keyBytes, commandType, null); cmd.setMergeCommands(mergeCommands); cmd.setWriteFuture(new FutureImpl<Boolean>()); cmd.setMergeCount(mergeCount); cmd.setIoBuffer(IoBuffer.wrap(buf)); return cmd; } else { BinaryGetMultiCommand result = (BinaryGetMultiCommand) commandCollector.getResult(); result.setMergeCount(mergeCount); result.setMergeCommands(mergeCommands); return result; } }
@SuppressWarnings("unchecked") private final Command mergeGetCommands( final Command currentCmd, final Queue writeQueue, final Queue<Command> executingCmds, CommandType expectedCommandType) { Map<Object, Command> mergeCommands = null; int mergeCount = 1; final CommandCollector commandCollector = creatCommandCollector(); currentCmd.setStatus(OperationStatus.WRITING); commandCollector.visit(currentCmd); while (mergeCount < mergeFactor) { Command nextCmd = (Command) writeQueue.peek(); if (nextCmd == null) { break; } if (nextCmd.isCancel()) { writeQueue.remove(); continue; } if (nextCmd.getCommandType() == expectedCommandType) { if (mergeCommands == null) { // lazy initialize mergeCommands = new HashMap<Object, Command>(mergeFactor / 2); mergeCommands.put(currentCmd.getKey(), currentCmd); } if (log.isDebugEnabled()) { log.debug("Merge get command:" + nextCmd.toString()); } nextCmd.setStatus(OperationStatus.WRITING); Command removedCommand = (Command) writeQueue.remove(); // If the key is exists,add the command to associated list. if (mergeCommands.containsKey(removedCommand.getKey())) { final AssocCommandAware mergedGetCommand = (AssocCommandAware) mergeCommands.get(removedCommand.getKey()); if (mergedGetCommand.getAssocCommands() == null) { mergedGetCommand.setAssocCommands(new ArrayList<Command>(5)); } mergedGetCommand.getAssocCommands().add(removedCommand); } else { commandCollector.visit(nextCmd); mergeCommands.put(removedCommand.getKey(), removedCommand); } mergeCount++; } else { break; } } commandCollector.finish(); if (mergeCount == 1) { return currentCmd; } else { if (log.isDebugEnabled()) { log.debug("Merge optimieze:merge " + mergeCount + " get commands"); } return newMergedCommand(mergeCommands, mergeCount, commandCollector, expectedCommandType); } }