Search in sources :

Example 1 with RedisFuture

use of io.lettuce.core.RedisFuture in project jetcache by alibaba.

the class RedisLettuceCacheFailTest method mockFuture.

private RedisFuture mockFuture(Object value, Throwable ex) {
    RedisFuture redisFuture = mock(RedisFuture.class);
    when(redisFuture.handle(any())).thenAnswer((invoke) -> {
        BiFunction function = invoke.getArgument(0);
        Object resultData = function.apply(value, ex);
        return CompletableFuture.completedFuture(resultData);
    });
    return redisFuture;
}
Also used : BiFunction(java.util.function.BiFunction) RedisFuture(io.lettuce.core.RedisFuture)

Example 2 with RedisFuture

use of io.lettuce.core.RedisFuture in project austin by ZhongFuCheng3y.

the class AustinSink method realTimeData.

/**
 * 实时数据存入Redis
 * 1.用户维度(查看用户当天收到消息的链路详情),数量级大,只保留当天
 * 2.消息模板维度(查看消息模板整体下发情况),数量级小,保留30天
 *
 * @param info
 */
private void realTimeData(AnchorInfo info) {
    try {
        LettuceRedisUtils.pipeline(redisAsyncCommands -> {
            List<RedisFuture<?>> redisFutures = new ArrayList<>();
            /**
             * 1.构建userId维度的链路信息 数据结构list:{key,list}
             * key:userId,listValue:[{timestamp,state,businessId},{timestamp,state,businessId}]
             */
            SimpleAnchorInfo simpleAnchorInfo = SimpleAnchorInfo.builder().businessId(info.getBusinessId()).state(info.getState()).timestamp(info.getTimestamp()).build();
            for (String id : info.getIds()) {
                redisFutures.add(redisAsyncCommands.lpush(id.getBytes(), JSON.toJSONString(simpleAnchorInfo).getBytes()));
                redisFutures.add(redisAsyncCommands.expire(id.getBytes(), (DateUtil.endOfDay(new Date()).getTime() - DateUtil.current()) / 1000));
            }
            /**
             * 2.构建消息模板维度的链路信息 数据结构hash:{key,hash}
             * key:businessId,hashValue:{state,stateCount}
             */
            redisFutures.add(redisAsyncCommands.hincrby(String.valueOf(info.getBusinessId()).getBytes(), String.valueOf(info.getState()).getBytes(), info.getIds().size()));
            redisFutures.add(redisAsyncCommands.expire(String.valueOf(info.getBusinessId()).getBytes(), (DateUtil.offsetDay(new Date(), 30).getTime()) / 1000));
            return redisFutures;
        });
    } catch (Exception e) {
        log.error("AustinSink#invoke error: {}", Throwables.getStackTraceAsString(e));
    }
}
Also used : SimpleAnchorInfo(com.java3y.austin.common.domain.SimpleAnchorInfo) RedisFuture(io.lettuce.core.RedisFuture) ArrayList(java.util.ArrayList) Date(java.util.Date)

Example 3 with RedisFuture

use of io.lettuce.core.RedisFuture in project api-layer by zowe.

the class RedisOperatorTest method givenRedisExecutionExceptionNotOutOfMemory_thenThrowRetryableRedisException.

@Test
void givenRedisExecutionExceptionNotOutOfMemory_thenThrowRetryableRedisException() throws ExecutionException, InterruptedException {
    RedisFuture<Boolean> future = (RedisFuture<Boolean>) mock(RedisFuture.class);
    when(redisCommands.hsetnx(any(), any(), any())).thenReturn(future);
    when(future.get()).thenThrow(new ExecutionException(new RedisCommandExecutionException("error")));
    assertThrows(RetryableRedisException.class, () -> underTest.create(REDIS_ENTRY));
}
Also used : RedisCommandExecutionException(io.lettuce.core.RedisCommandExecutionException) RedisFuture(io.lettuce.core.RedisFuture) RedisCommandExecutionException(io.lettuce.core.RedisCommandExecutionException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test)

Example 4 with RedisFuture

use of io.lettuce.core.RedisFuture in project lettuce-core by lettuce-io.

the class RedisClusterSetupTest method atLeastOnceForgetNodeFailover.

@Test
public void atLeastOnceForgetNodeFailover() throws Exception {
    clusterClient.setOptions(ClusterClientOptions.builder().topologyRefreshOptions(PERIODIC_REFRESH_ENABLED).build());
    RedisAdvancedClusterAsyncCommands<String, String> clusterConnection = clusterClient.connect().async();
    clusterClient.setOptions(ClusterClientOptions.create());
    ClusterSetup.setup2Masters(clusterHelper);
    assertRoutedExecution(clusterConnection);
    RedisClusterNode partition1 = getOwnPartition(redis1);
    RedisClusterNode partition2 = getOwnPartition(redis2);
    RedisClusterAsyncCommands<String, String> node1Connection = clusterConnection.getConnection(partition1.getUri().getHost(), partition1.getUri().getPort());
    RedisClusterAsyncCommands<String, String> node2Connection = clusterConnection.getConnection(partition2.getUri().getHost(), partition2.getUri().getPort());
    shiftAllSlotsToNode1();
    suspendConnection(node2Connection);
    List<RedisFuture<String>> futures = new ArrayList<>();
    // 15891
    futures.add(clusterConnection.set("t", "value"));
    // 16023
    futures.add(clusterConnection.set("p", "value"));
    // 6373
    clusterConnection.set("A", "value").get(1, TimeUnit.SECONDS);
    for (RedisFuture<String> future : futures) {
        assertThat(future.isDone()).isFalse();
        assertThat(future.isCancelled()).isFalse();
    }
    redis1.clusterForget(partition2.getNodeId());
    redis2.clusterForget(partition1.getNodeId());
    Partitions partitions = clusterClient.getPartitions();
    partitions.remove(partition2);
    partitions.getPartition(0).setSlots(Arrays.stream(createSlots(0, 16384)).boxed().collect(Collectors.toList()));
    partitions.updateCache();
    clusterClient.updatePartitionsInConnections();
    Wait.untilTrue(() -> TestFutures.areAllDone(futures)).waitOrTimeout();
    assertRoutedExecution(clusterConnection);
    clusterConnection.getStatefulConnection().close();
}
Also used : Partitions(io.lettuce.core.cluster.models.partitions.Partitions) RedisClusterNode(io.lettuce.core.cluster.models.partitions.RedisClusterNode) RedisFuture(io.lettuce.core.RedisFuture) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Example 5 with RedisFuture

use of io.lettuce.core.RedisFuture in project micronaut-redis by micronaut-projects.

the class RedisSessionStore method saveSessionDelta.

private CompletableFuture<RedisSession> saveSessionDelta(RedisSession session, Map<byte[], byte[]> changes) {
    Duration maxInactiveInterval = session.getMaxInactiveInterval();
    long expirySeconds = maxInactiveInterval.getSeconds();
    byte[] sessionKey = getSessionKey(session.getId());
    byte[] sessionIdBytes = session.getId().getBytes(charset);
    if (expirySeconds == 0) {
        // delete the expired session
        RedisFuture<Long> deleteOp = redisKeyAsyncCommands.del(getExpiryKey(session));
        return deleteOp.thenCompose(ignore -> redisHashAsyncCommands.hmset(sessionKey, changes)).thenApply(ignore -> session).toCompletableFuture();
    }
    return redisHashAsyncCommands.hmset(sessionKey, changes).thenCompose(ignore -> {
        try {
            if (session.isNew()) {
                session.clearModifications();
                baseRedisAsyncCommands.publish(sessionCreatedTopic, sessionIdBytes).whenComplete((aLong, throwable12) -> {
                    if (throwable12 != null) {
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error publishing session creation event: " + throwable12.getMessage(), throwable12);
                        }
                    }
                });
            } else {
                session.clearModifications();
            }
        } catch (Throwable e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Error publishing session creation event: " + e.getMessage(), e);
            }
        }
        long fiveMinutesAfterExpires = expirySeconds + TimeUnit.MINUTES.toSeconds(EXPIRATION_SECONDS);
        byte[] expiryKey = getExpiryKey(session);
        double expireTimeScore = Long.valueOf(Instant.now().plus(expirySeconds, ChronoUnit.SECONDS).toEpochMilli()).doubleValue();
        CompletableFuture<Boolean> expireOp = redisKeyAsyncCommands.expire(sessionKey, fiveMinutesAfterExpires).toCompletableFuture();
        CompletableFuture<String> saveExpiryOp = redisStringAsyncCommands.setex(expiryKey, expirySeconds, String.valueOf(expirySeconds).getBytes()).toCompletableFuture();
        CompletableFuture<Long> saveActiveSessionOp = redisSortedSetAsyncCommands.zadd(activeSessionsSet, expireTimeScore, sessionIdBytes).toCompletableFuture();
        return CompletableFuture.allOf(expireOp, saveExpiryOp, saveActiveSessionOp).thenApply(ignore2 -> session);
    }).toCompletableFuture();
}
Also used : io.lettuce.core.api.async(io.lettuce.core.api.async) RedisPubSubAsyncCommandsImpl(io.lettuce.core.pubsub.RedisPubSubAsyncCommandsImpl) SessionCreatedEvent(io.micronaut.session.event.SessionCreatedEvent) LoggerFactory(org.slf4j.LoggerFactory) StatefulConnection(io.lettuce.core.api.StatefulConnection) PreDestroy(javax.annotation.PreDestroy) TaskExecutors(io.micronaut.scheduling.TaskExecutors) StatefulRedisConnection(io.lettuce.core.api.StatefulRedisConnection) Duration(java.time.Duration) SessionExpiredEvent(io.micronaut.session.event.SessionExpiredEvent) BeanLocator(io.micronaut.context.BeanLocator) TypeHint(io.micronaut.core.annotation.TypeHint) ObjectSerializer(io.micronaut.core.serialize.ObjectSerializer) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StatefulRedisClusterConnection(io.lettuce.core.cluster.api.StatefulRedisClusterConnection) StringUtils(io.micronaut.core.util.StringUtils) RedisPubSubAdapter(io.lettuce.core.pubsub.RedisPubSubAdapter) Range(io.lettuce.core.Range) Replaces(io.micronaut.context.annotation.Replaces) Named(jakarta.inject.Named) java.util(java.util) RedisPubSubReactiveCommandsImpl(io.lettuce.core.pubsub.RedisPubSubReactiveCommandsImpl) RedisSession(io.micronaut.configuration.lettuce.session.RedisSessionStore.RedisSession) ArgumentConversionContext(io.micronaut.core.convert.ArgumentConversionContext) SessionDeletedEvent(io.micronaut.session.event.SessionDeletedEvent) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) RedisAdvancedClusterAsyncCommands(io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands) Primary(io.micronaut.context.annotation.Primary) Charset(java.nio.charset.Charset) io.micronaut.session(io.micronaut.session) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RedisFuture(io.lettuce.core.RedisFuture) Requires(io.micronaut.context.annotation.Requires) RedisPubSubCommands(io.lettuce.core.pubsub.api.sync.RedisPubSubCommands) MutableConvertibleValues(io.micronaut.core.convert.value.MutableConvertibleValues) ExecutorService(java.util.concurrent.ExecutorService) RedisConnectionUtil(io.micronaut.configuration.lettuce.RedisConnectionUtil) ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) Logger(org.slf4j.Logger) RedisAdvancedClusterCommands(io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands) StatefulRedisPubSubConnection(io.lettuce.core.pubsub.StatefulRedisPubSubConnection) ApplicationEventPublisher(io.micronaut.context.event.ApplicationEventPublisher) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) CollectionUtils(io.micronaut.core.util.CollectionUtils) io.lettuce.core.api.sync(io.lettuce.core.api.sync) CompletableFuture(java.util.concurrent.CompletableFuture) Duration(java.time.Duration)

Aggregations

RedisFuture (io.lettuce.core.RedisFuture)9 StatefulConnection (io.lettuce.core.api.StatefulConnection)2 StatefulRedisConnection (io.lettuce.core.api.StatefulRedisConnection)2 RedisClusterNode (io.lettuce.core.cluster.models.partitions.RedisClusterNode)2 ByteArrayCodec (io.lettuce.core.codec.ByteArrayCodec)2 ArrayList (java.util.ArrayList)2 Collectors (java.util.stream.Collectors)2 Test (org.junit.jupiter.api.Test)2 SimpleAnchorInfo (com.java3y.austin.common.domain.SimpleAnchorInfo)1 ConnectResource (com.lcache.connect.ConnectResource)1 CacheConfigModel (com.lcache.core.model.CacheConfigModel)1 LettuceConnectResource (com.lcache.extend.handle.redis.lettuce.connect.LettuceConnectResource)1 LettucePipelineExecutor (com.lcache.extend.handle.redis.lettuce.pipeline.LettucePipelineExecutor)1 Range (io.lettuce.core.Range)1 RedisCommandExecutionException (io.lettuce.core.RedisCommandExecutionException)1 io.lettuce.core.api.async (io.lettuce.core.api.async)1 io.lettuce.core.api.sync (io.lettuce.core.api.sync)1 StatefulRedisClusterConnection (io.lettuce.core.cluster.api.StatefulRedisClusterConnection)1 RedisAdvancedClusterAsyncCommands (io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands)1 RedisAdvancedClusterCommands (io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands)1