org.redisson.client.protocol.CommandData Java Examples

The following examples show how to use org.redisson.client.protocol.CommandData. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedisClientTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPipelineBigResponse() throws InterruptedException, ExecutionException {
    RedisConnection conn = redisClient.connect();

    List<CommandData<?, ?>> commands = new ArrayList<CommandData<?, ?>>();
    for (int i = 0; i < 1000; i++) {
        CommandData<String, String> cmd1 = conn.create(null, RedisCommands.PING);
        commands.add(cmd1);
    }

    RPromise<Void> p = new RedissonPromise<Void>();
    conn.send(new CommandsData(p, commands, false, false));

    for (CommandData<?, ?> commandData : commands) {
        commandData.getPromise().get();
    }

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #2
Source File: RedisClientTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testPipeline() throws InterruptedException, ExecutionException {
    RedisConnection conn = redisClient.connect();

    conn.sync(StringCodec.INSTANCE, RedisCommands.SET, "test", 0);

    List<CommandData<?, ?>> commands = new ArrayList<CommandData<?, ?>>();
    CommandData<String, String> cmd1 = conn.create(null, RedisCommands.PING);
    commands.add(cmd1);
    CommandData<Long, Long> cmd2 = conn.create(null, RedisCommands.INCR, "test");
    commands.add(cmd2);
    CommandData<Long, Long> cmd3 = conn.create(null, RedisCommands.INCR, "test");
    commands.add(cmd3);
    CommandData<String, String> cmd4 = conn.create(null, RedisCommands.PING);
    commands.add(cmd4);

    RPromise<Void> p = new RedissonPromise<Void>();
    conn.send(new CommandsData(p, commands, false, false));

    assertThat(cmd1.getPromise().get()).isEqualTo("PONG");
    assertThat(cmd2.getPromise().get()).isEqualTo(1);
    assertThat(cmd3.getPromise().get()).isEqualTo(2);
    assertThat(cmd4.getPromise().get()).isEqualTo("PONG");

    conn.sync(RedisCommands.FLUSHDB);
}
 
Example #3
Source File: CommandsQueue.java    From redisson with Apache License 2.0 6 votes vote down vote up
private void sendData(Channel ch) {
    QueueCommandHolder command = queue.peek();
    if (command != null && command.trySend()) {
        QueueCommand data = command.getCommand();
        List<CommandData<Object, Object>> pubSubOps = data.getPubSubOperations();
        if (!pubSubOps.isEmpty()) {
            for (CommandData<Object, Object> cd : pubSubOps) {
                for (Object channel : cd.getParams()) {
                    ch.pipeline().get(CommandPubSubDecoder.class).addPubSubCommand((ChannelName) channel, cd);
                }
            }
        } else {
            ch.attr(CURRENT_COMMAND).set(data);
        }

        command.getChannelPromise().addListener(listener);
        ch.writeAndFlush(data, command.getChannelPromise());
    }
}
 
Example #4
Source File: CommandsQueue.java    From redisson with Apache License 2.0 6 votes vote down vote up
public void sendNextCommand(Channel channel) {
    QueueCommand command = channel.attr(CommandsQueue.CURRENT_COMMAND).getAndSet(null);
    if (command != null) {
        queue.poll();
    } else {
        QueueCommandHolder c = queue.peek();
        if (c != null) {
            QueueCommand data = c.getCommand();
            List<CommandData<Object, Object>> pubSubOps = data.getPubSubOperations();
            if (!pubSubOps.isEmpty()) {
                queue.poll();
            }
        }
    }
    sendData(channel);
}
 
Example #5
Source File: RedisConnectionInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter
private static void beforeSend(@Advice.This RedisConnection connection,
                               @Advice.Argument(0) Object args,
                               @Nullable @Advice.Local("span") Span span) {
    span = RedisSpanUtils.createRedisSpan("");
    if (span != null) {
        // get command
        if (args instanceof CommandsData) {
            List<CommandData<?, ?>> commands = ((CommandsData) args).getCommands();
            if (commands != null && !commands.isEmpty()) {
                span.appendToName(commands.get(0).getCommand().getName()).appendToName("... [bulk]");
            }
        } else if (args instanceof CommandData) {
            span.appendToName(((CommandData) args).getCommand().getName());
        }

        // get connection address
        Channel channel = connection.getChannel();
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        span.getContext().getDestination()
            .withAddress(remoteAddress.getAddress().getHostAddress())
            .withPort(remoteAddress.getPort());
    }
}
 
Example #6
Source File: CommandPubSubDecoder.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected Decoder<Object> selectDecoder(CommandData<Object, Object> data, List<Object> parts) {
    if (parts != null) {
        if (data != null && parts.size() == 1 && "pong".equals(parts.get(0))) {
            return data.getCodec().getValueDecoder();
        }
        if (parts.size() == 1) {
            return ByteArrayCodec.INSTANCE.getValueDecoder();
        }
        if (parts.size() == 2 && "pmessage".equals(parts.get(0))) {
            return ByteArrayCodec.INSTANCE.getValueDecoder();
        }
        
        if (parts.size() == 2 && "message".equals(parts.get(0))) {
            byte[] channelName = (byte[]) parts.get(1);
            return getDecoder(parts, channelName);
        }
        if (parts.size() == 3 && "pmessage".equals(parts.get(0))) {
            byte[] patternName = (byte[]) parts.get(1);
            return getDecoder(parts, patternName);
        }
    }
    
    if (data != null && data.getCommand().getName().equals(RedisCommands.PING.getName())) {
        return StringCodec.INSTANCE.getValueDecoder();
    }
    
    return super.selectDecoder(data, parts);
}
 
Example #7
Source File: RedisCommonBatchExecutor.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void sendCommand(RPromise<Void> attemptPromise, RedisConnection connection) {
    boolean isAtomic = options.getExecutionMode() != ExecutionMode.IN_MEMORY;
    boolean isQueued = options.getExecutionMode() == ExecutionMode.REDIS_READ_ATOMIC 
                            || options.getExecutionMode() == ExecutionMode.REDIS_WRITE_ATOMIC;

    List<CommandData<?, ?>> list = new ArrayList<>(entry.getCommands().size());
    if (source.getRedirect() == Redirect.ASK) {
        RPromise<Void> promise = new RedissonPromise<Void>();
        list.add(new CommandData<Void, Void>(promise, StringCodec.INSTANCE, RedisCommands.ASKING, new Object[] {}));
    } 
    for (CommandData<?, ?> c : entry.getCommands()) {
        if ((c.getPromise().isCancelled() || c.getPromise().isSuccess()) 
                && !isWaitCommand(c) 
                    && !isAtomic) {
            // skip command
            continue;
        }
        list.add(c);
    }
    
    if (list.isEmpty()) {
        writeFuture = connection.getChannel().newPromise();
        attemptPromise.trySuccess(null);
        timeout.cancel();
        return;
    }
    
    writeFuture = connection.send(new CommandsData(attemptPromise, list, options.isSkipResult(), isAtomic, isQueued, options.getSyncSlaves() > 0));
}
 
Example #8
Source File: CommandBatchEncoder.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, CommandsData msg, ByteBuf out) throws Exception {
    CommandEncoder encoder = ctx.pipeline().get(CommandEncoder.class);
    for (CommandData<?, ?> commandData : msg.getCommands()) {
        encoder.encode(ctx, commandData, out);
    }
}
 
Example #9
Source File: CommandEncoder.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, CommandData<?, ?> msg, ByteBuf out) throws Exception {
    try {
        out.writeByte(ARGS_PREFIX);
        int len = 1 + msg.getParams().length;
        if (msg.getCommand().getSubName() != null) {
            len++;
        }
        out.writeCharSequence(Long.toString(len), CharsetUtil.US_ASCII);
        out.writeBytes(CRLF);
        
        writeArgument(out, msg.getCommand().getName().getBytes(CharsetUtil.UTF_8));
        if (msg.getCommand().getSubName() != null) {
            writeArgument(out, msg.getCommand().getSubName().getBytes(CharsetUtil.UTF_8));
        }

        for (Object param : msg.getParams()) {
            ByteBuf buf = encode(param);
            writeArgument(out, buf);
            if (!(param instanceof ByteBuf)) {
                buf.release();
            }
        }
        
        if (log.isTraceEnabled()) {
            String info = out.toString(CharsetUtil.UTF_8);
            if (RedisCommands.AUTH.equals(msg.getCommand())) {
                info = info.substring(0, info.indexOf(RedisCommands.AUTH.getName()) + RedisCommands.AUTH.getName().length()) + "(password masked)";
            }
            log.trace("channel: {} message: {}", ctx.channel(), info);
        }
    } catch (Exception e) {
        msg.tryFailure(e);
        throw e;
    }
}
 
Example #10
Source File: PingConnectionHandler.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void sendPing(ChannelHandlerContext ctx) {
    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
    CommandData<?, ?> commandData = connection.getCurrentCommand();
    RFuture<String> future;
    if (commandData == null || !commandData.isBlockingCommand()) {
        future = connection.async(StringCodec.INSTANCE, RedisCommands.PING);
    } else {
        future = null;
    }

    config.getTimer().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (connection.isClosed()) {
                return;
            }
            if (future != null
                    && (future.cancel(false) || !future.isSuccess())) {
                ctx.channel().close();
                if (future.cause() != null) {
                    log.error("Unable to send PING command over channel: " + ctx.channel(), future.cause());
                }
                log.debug("channel: {} closed due to PING response timeout set in {} ms", ctx.channel(), config.getPingConnectionInterval());
            } else {
                sendPing(ctx);
            }
        }
    }, config.getPingConnectionInterval(), TimeUnit.MILLISECONDS);
}
 
Example #11
Source File: ConnectionWatchdog.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void refresh(RedisConnection connection, Channel channel) {
    CommandData<?, ?> currentCommand = connection.getCurrentCommand();
    connection.fireConnected();
    connection.updateChannel(channel);
    
    if (connection.isFastReconnect()) {
        connection.clearFastReconnect();
    }

    reattachBlockingQueue(connection, currentCommand);            
    reattachPubSub(connection);
}
 
Example #12
Source File: RedisConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void close() {
    CommandData<?, ?> command = getCurrentCommand();
    if (!isActive()
            || (command != null && command.isBlockingCommand())
                || !connectionPromise.isDone()) {
        channel.close();
    } else {
        RFuture<Void> f = async(RedisCommands.QUIT);
        f.onComplete((res, e) -> {
            channel.close();
        });
    }
}
 
Example #13
Source File: RedisConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
public <T, R> RFuture<R> async(long timeout, Codec encoder, RedisCommand<T> command, Object... params) {
    RPromise<R> promise = new RedissonPromise<R>();
    if (timeout == -1) {
        timeout = redisClient.getCommandTimeout();
    }
    
    if (redisClient.getEventLoopGroup().isShuttingDown()) {
        RedissonShutdownException cause = new RedissonShutdownException("Redisson is shutdown");
        return RedissonPromise.newFailedFuture(cause);
    }

    Timeout scheduledFuture = redisClient.getTimer().newTimeout(t -> {
        RedisTimeoutException ex = new RedisTimeoutException("Command execution timeout for command: "
                + LogHelper.toString(command, params) + ", Redis client: " + redisClient);
        promise.tryFailure(ex);
    }, timeout, TimeUnit.MILLISECONDS);
    
    promise.onComplete((res, e) -> {
        scheduledFuture.cancel();
    });
    
    ChannelFuture writeFuture = send(new CommandData<T, R>(promise, encoder, command, params));
    writeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                promise.tryFailure(future.cause());
            }
        }
    });
    return promise;
}
 
Example #14
Source File: RedisConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
public CommandData<?, ?> getCurrentCommand() {
    QueueCommand command = channel.attr(CommandsQueue.CURRENT_COMMAND).get();
    if (command instanceof CommandData) {
        return (CommandData<?, ?>) command;
    }
    return null;
}
 
Example #15
Source File: LogHelper.java    From redisson with Apache License 2.0 5 votes vote down vote up
public static String toString(Object object) {
        if (object == null) {
            return "null";
        } else if (object instanceof String) {
            return toStringString((String) object);
        } else if (object.getClass().isArray()) {
            return toArrayString(object);
        } else if (object instanceof Collection) {
            return toCollectionString((Collection<?>) object);
        } else if (object instanceof CommandData) {
            CommandData<?, ?> cd = (CommandData<?, ?>) object;
            if (RedisCommands.AUTH.equals(cd.getCommand())) {
                return cd.getCommand() + ", params: (password masked)";
            }
            return cd.getCommand() + ", params: " + LogHelper.toString(cd.getParams());
        } else if (object instanceof ByteBuf) {
            final ByteBuf byteBuf = (ByteBuf) object;
            // can't be used due to Buffer Leak error is appeared in log
//            if (byteBuf.refCnt() > 0) {
//                if (byteBuf.writerIndex() > MAX_BYTEBUF_LOG_SIZE) {
//                    return new StringBuilder(byteBuf.toString(0, MAX_BYTEBUF_LOG_SIZE, CharsetUtil.UTF_8)).append("...").toString();
//                } else {
//                    return byteBuf.toString(0, byteBuf.writerIndex(), CharsetUtil.UTF_8);
//                }
//            }
            return byteBuf.toString();
        } else {
            return String.valueOf(object);
        }
    }
 
Example #16
Source File: RedisConnectionMethodInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private void addCommandData(StringBuilder dbStatement, CommandData commandData) {
    dbStatement.append(commandData.getCommand().getName());
    if (commandData.getParams() != null) {
        for (Object param : commandData.getParams()) {
            dbStatement.append(" ").append(param instanceof ByteBuf ? "?" : String.valueOf(param.toString()));
        }
    }
}
 
Example #17
Source File: CommandPubSubDecoder.java    From redisson with Apache License 2.0 4 votes vote down vote up
public void addPubSubCommand(ChannelName channel, CommandData<Object, Object> data) {
    String operation = data.getCommand().getName().toLowerCase();
    commands.put(new PubSubKey(channel, operation), data);
}
 
Example #18
Source File: RedisPubSubConnection.java    From redisson with Apache License 2.0 4 votes vote down vote up
private <T, R> ChannelFuture async(MultiDecoder<Object> messageDecoder, RedisCommand<T> command, Object... params) {
    RPromise<R> promise = new RedissonPromise<R>();
    return channel.writeAndFlush(new CommandData<T, R>(promise, messageDecoder, null, command, params));
}
 
Example #19
Source File: RedisConnection.java    From redisson with Apache License 2.0 4 votes vote down vote up
public <T, R> CommandData<T, R> create(Codec encoder, RedisCommand<T> command, Object... params) {
    RPromise<R> promise = new RedissonPromise<R>();
    return new CommandData<T, R>(promise, encoder, command, params);
}
 
Example #20
Source File: RedisConnection.java    From redisson with Apache License 2.0 4 votes vote down vote up
public <T, R> R sync(Codec encoder, RedisCommand<T> command, Object... params) {
    RPromise<R> promise = new RedissonPromise<R>();
    send(new CommandData<T, R>(promise, encoder, command, params));
    return await(promise);
}
 
Example #21
Source File: RedisConnection.java    From redisson with Apache License 2.0 4 votes vote down vote up
public <T, R> ChannelFuture send(CommandData<T, R> data) {
    return channel.writeAndFlush(data);
}
 
Example #22
Source File: MasterSlaveEntry.java    From redisson with Apache License 2.0 4 votes vote down vote up
private void reattachBlockingQueue(CommandData<?, ?> commandData) {
    if (commandData == null
            || !commandData.isBlockingCommand()
                || commandData.getPromise().isDone()) {
        return;
    }

    String key = null;
    for (int i = 0; i < commandData.getParams().length; i++) {
        Object param = commandData.getParams()[i];
        if ("STREAMS".equals(param)) {
            key = (String) commandData.getParams()[i+1];
            break;
        }
    }
    if (key == null) {
        key = (String) commandData.getParams()[0];
    }

    MasterSlaveEntry entry = connectionManager.getEntry(key);
    if (entry == null) {
        connectionManager.newTimeout(timeout ->
                reattachBlockingQueue(commandData), 1, TimeUnit.SECONDS);
        return;
    }

    RFuture<RedisConnection> newConnectionFuture = entry.connectionWriteOp(commandData.getCommand());
    newConnectionFuture.onComplete((newConnection, e) -> {
        if (e != null) {
            connectionManager.newTimeout(timeout ->
                    reattachBlockingQueue(commandData), 1, TimeUnit.SECONDS);
            return;
        }

        if (commandData.getPromise().isDone()) {
            entry.releaseWrite(newConnection);
            return;
        }

        ChannelFuture channelFuture = newConnection.send(commandData);
        channelFuture.addListener(future -> {
            if (!future.isSuccess()) {
                connectionManager.newTimeout(timeout ->
                        reattachBlockingQueue(commandData), 1, TimeUnit.SECONDS);
            }
        });
        commandData.getPromise().onComplete((r, ex) -> {
            entry.releaseWrite(newConnection);
        });
    });
}
 
Example #23
Source File: RedisCommonBatchExecutor.java    From redisson with Apache License 2.0 4 votes vote down vote up
private void free(Entry entry) {
    for (CommandData<?, ?> command : entry.getCommands()) {
        free(command.getParams());
    }
}
 
Example #24
Source File: RedisCommonBatchExecutor.java    From redisson with Apache License 2.0 4 votes vote down vote up
protected boolean isWaitCommand(CommandData<?, ?> c) {
    return c.getCommand().getName().equals(RedisCommands.WAIT.getName());
}
 
Example #25
Source File: CommandBatchService.java    From redisson with Apache License 2.0 4 votes vote down vote up
protected boolean isWaitCommand(CommandData<?, ?> c) {
    return c.getCommand().getName().equals(RedisCommands.WAIT.getName());
}