Search in sources :

Example 1 with RedisCommand

use of io.lettuce.core.protocol.RedisCommand in project lettuce-core by lettuce-io.

the class CustomCommandIntegrationTests method standaloneAsyncBatchTransaction.

@Test
void standaloneAsyncBatchTransaction() {
    RedisCommand<String, String, String> multi = new Command<>(CommandType.MULTI, new StatusOutput<>(StringCodec.UTF8));
    RedisCommand<String, String, String> set = new Command<>(CommandType.SET, new StatusOutput<>(StringCodec.UTF8), new CommandArgs<>(StringCodec.UTF8).addKey("key").add("value"));
    RedisCommand<String, String, TransactionResult> exec = new Command<>(CommandType.EXEC, null);
    AsyncCommand<String, String, String> async1 = new AsyncCommand<>(multi);
    AsyncCommand<String, String, String> async2 = new AsyncCommand<>(set);
    AsyncCommand<String, String, TransactionResult> async3 = new AsyncCommand<>(exec);
    getStandaloneConnection().dispatch(Arrays.asList(async1, async2, async3));
    assertThat(TestFutures.getOrTimeout(async1.toCompletableFuture())).isEqualTo("OK");
    assertThat(TestFutures.getOrTimeout(async2.toCompletableFuture())).isEqualTo("OK");
    TransactionResult transactionResult = TestFutures.getOrTimeout(async3.toCompletableFuture());
    assertThat(transactionResult.wasDiscarded()).isFalse();
    assertThat(transactionResult.<String>get(0)).isEqualTo("OK");
}
Also used : TransactionResult(io.lettuce.core.TransactionResult) Command(io.lettuce.core.protocol.Command) AsyncCommand(io.lettuce.core.protocol.AsyncCommand) RedisCommand(io.lettuce.core.protocol.RedisCommand) AsyncCommand(io.lettuce.core.protocol.AsyncCommand) Test(org.junit.jupiter.api.Test)

Example 2 with RedisCommand

use of io.lettuce.core.protocol.RedisCommand in project lettuce-core by lettuce-io.

the class NodeSelectionInvocationHandler method handleInvocation.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        if (method.getName().equals("commands") && args.length == 0) {
            return proxy;
        }
        Method targetMethod = findMethod(commandsInterface, method, connectionMethod);
        if (targetMethod == null) {
            Method nodeSelectionMethod = findMethod(NodeSelectionSupport.class, method, nodeSelectionMethods);
            return nodeSelectionMethod.invoke(selection, args);
        }
        Map<RedisClusterNode, CompletableFuture<? extends StatefulRedisConnection<?, ?>>> connections = new LinkedHashMap<>(selection.size(), 1);
        connections.putAll(selection.statefulMap());
        Map<RedisClusterNode, Object> executions = new LinkedHashMap<>(selection.size(), 1);
        AtomicLong timeout = new AtomicLong();
        for (Map.Entry<RedisClusterNode, CompletableFuture<? extends StatefulRedisConnection<?, ?>>> entry : connections.entrySet()) {
            CompletableFuture<? extends StatefulRedisConnection<?, ?>> connection = entry.getValue();
            CompletableFuture<Object> result = connection.thenCompose(it -> {
                try {
                    Object resultValue = doInvoke(args, targetMethod, it);
                    if (timeoutProvider != null && resultValue instanceof RedisCommand && timeout.get() == 0) {
                        timeout.set(timeoutProvider.getTimeoutNs((RedisCommand) resultValue));
                    }
                    if (resultValue instanceof CompletionStage<?>) {
                        return (CompletionStage<Object>) resultValue;
                    }
                    return CompletableFuture.completedFuture(resultValue);
                } catch (InvocationTargetException e) {
                    CompletableFuture<Object> future = new CompletableFuture<>();
                    future.completeExceptionally(e.getTargetException());
                    return future;
                } catch (Exception e) {
                    CompletableFuture<Object> future = new CompletableFuture<>();
                    future.completeExceptionally(e);
                    return future;
                }
            });
            executions.put(entry.getKey(), result);
        }
        return getExecutions(executions, timeout.get());
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) RedisCommandExecutionException(io.lettuce.core.RedisCommandExecutionException) RedisCommandTimeoutException(io.lettuce.core.RedisCommandTimeoutException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) StatefulRedisConnection(io.lettuce.core.api.StatefulRedisConnection) LinkedHashMap(java.util.LinkedHashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicLong(java.util.concurrent.atomic.AtomicLong) RedisClusterNode(io.lettuce.core.cluster.models.partitions.RedisClusterNode) RedisCommand(io.lettuce.core.protocol.RedisCommand) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionStage(java.util.concurrent.CompletionStage)

Example 3 with RedisCommand

use of io.lettuce.core.protocol.RedisCommand in project uavstack by uavorg.

the class Lettuce5CommandHandlerIT method doWriteStart.

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object doWriteStart(Object[] args) {
    RedisCommand cmdRc = (RedisCommand) args[0];
    ProtocolKeyword cmd = (ProtocolKeyword) cmdRc.getType();
    String host = (String) args[1];
    Integer port = (Integer) args[2];
    String targetURL = "redis://" + host + ":" + port;
    String redisAction = cmd.toString();
    if (logger.isDebugable()) {
        logger.debug("REDIS INVOKE START: " + targetURL + " action: " + redisAction, null);
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL);
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_ACTION, redisAction);
    params.put(CaptureConstants.INFO_CLIENT_APPID, appid);
    params.put(CaptureConstants.INFO_CLIENT_TYPE, "redis.client.Lettuce");
    // register adapter
    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "registerAdapter", Lettuce5ClientAdapter.class);
    ivcContextParams = (Map<String, Object>) UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap", InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.PRECAP, params, Lettuce5ClientAdapter.class, args);
    UAVServer.instance().runMonitorCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT, Monitor.CapturePhase.PRECAP, params);
    return null;
}
Also used : HashMap(java.util.HashMap) RedisCommand(io.lettuce.core.protocol.RedisCommand) ProtocolKeyword(io.lettuce.core.protocol.ProtocolKeyword)

Example 4 with RedisCommand

use of io.lettuce.core.protocol.RedisCommand in project lettuce-core by lettuce-io.

the class RedisChannelHandler method dispatch.

protected Collection<RedisCommand<K, V, ?>> dispatch(Collection<? extends RedisCommand<K, V, ?>> commands) {
    if (debugEnabled) {
        logger.debug("dispatching commands {}", commands);
    }
    if (tracingEnabled) {
        Collection<RedisCommand<K, V, ?>> withTracer = new ArrayList<>(commands.size());
        for (RedisCommand<K, V, ?> command : commands) {
            RedisCommand<K, V, ?> commandToUse = command;
            TraceContextProvider provider = CommandWrapper.unwrap(command, TraceContextProvider.class);
            if (provider == null) {
                commandToUse = new TracedCommand<>(command, clientResources.tracing().initialTraceContextProvider().getTraceContext());
            }
            withTracer.add(commandToUse);
        }
        return channelWriter.write(withTracer);
    }
    return channelWriter.write(commands);
}
Also used : TraceContextProvider(io.lettuce.core.tracing.TraceContextProvider) RedisCommand(io.lettuce.core.protocol.RedisCommand) ArrayList(java.util.ArrayList)

Example 5 with RedisCommand

use of io.lettuce.core.protocol.RedisCommand in project lettuce-core by lettuce-io.

the class BatchExecutableCommand method synchronize.

protected static Object synchronize(BatchTasks batchTasks, StatefulConnection<Object, Object> connection) {
    if (batchTasks == BatchTasks.EMPTY) {
        return null;
    }
    Duration timeout = connection.getTimeout();
    BatchException exception = null;
    List<RedisCommand<?, ?, ?>> failures = null;
    for (RedisCommand<?, ?, ?> batchTask : batchTasks) {
        try {
            Futures.await(timeout, (RedisFuture) batchTask);
        } catch (Exception e) {
            if (exception == null) {
                failures = new ArrayList<>();
                exception = new BatchException(failures);
            }
            failures.add(batchTask);
            exception.addSuppressed(e);
        }
    }
    if (exception != null) {
        throw exception;
    }
    return null;
}
Also used : RedisCommand(io.lettuce.core.protocol.RedisCommand) ArrayList(java.util.ArrayList) Duration(java.time.Duration) BatchException(io.lettuce.core.dynamic.batch.BatchException) ExecutionException(java.util.concurrent.ExecutionException) BatchException(io.lettuce.core.dynamic.batch.BatchException)

Aggregations

RedisCommand (io.lettuce.core.protocol.RedisCommand)8 Command (io.lettuce.core.protocol.Command)2 ArrayList (java.util.ArrayList)2 ExecutionException (java.util.concurrent.ExecutionException)2 BeforeEach (org.junit.jupiter.api.BeforeEach)2 RedisCommandExecutionException (io.lettuce.core.RedisCommandExecutionException)1 RedisCommandTimeoutException (io.lettuce.core.RedisCommandTimeoutException)1 TransactionResult (io.lettuce.core.TransactionResult)1 StatefulRedisConnection (io.lettuce.core.api.StatefulRedisConnection)1 RedisClusterNode (io.lettuce.core.cluster.models.partitions.RedisClusterNode)1 BatchException (io.lettuce.core.dynamic.batch.BatchException)1 MethodParametersAccessor (io.lettuce.core.dynamic.parameter.MethodParametersAccessor)1 AsyncCommand (io.lettuce.core.protocol.AsyncCommand)1 CommandArgs (io.lettuce.core.protocol.CommandArgs)1 CommandHandler (io.lettuce.core.protocol.CommandHandler)1 ProtocolKeyword (io.lettuce.core.protocol.ProtocolKeyword)1 TraceContextProvider (io.lettuce.core.tracing.TraceContextProvider)1 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)1 LocalAddress (io.netty.channel.local.LocalAddress)1 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)1