io.lettuce.core.api.async.RedisAsyncCommands Java Examples

The following examples show how to use io.lettuce.core.api.async.RedisAsyncCommands. 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: LettuceIntegrationLiveTest.java    From tutorials with MIT License 7 votes vote down vote up
@Test
public void givenValues_thenSaveAsRedisHashAsync() throws Exception {

    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();

    String recordName = "record1";
    String name = "FirstName";
    String value = "John";
    String surname = "LastName";
    String value1 = "Smith";

    asyncCommands.hset(recordName, name, value);
    asyncCommands.hset(recordName, surname, value1);
    RedisFuture<Map<String, String>> redisFuture = asyncCommands.hgetall(recordName);

    Map<String, String> record = redisFuture.get();

    Assert.assertEquals(record.get(name), value);
    Assert.assertEquals(record.get(surname), value1);
}
 
Example #2
Source File: LettuceIntegrationLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenARanking_thenSaveItInRedisSortedSetAsync() throws Exception {

    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();

    String key = "sortedset";

    asyncCommands.zadd(key, 1, "one");
    asyncCommands.zadd(key, 4, "zero");
    asyncCommands.zadd(key, 2, "two");

    RedisFuture<List<String>> values = asyncCommands.zrevrange(key, 0, 3);
    Assert.assertEquals("zero", values.get().get(0));

    values = asyncCommands.zrange(key, 0, 3);
    Assert.assertEquals("one", values.get().get(0));
}
 
Example #3
Source File: LettuceController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/lettuce-case")
@ResponseBody
public String lettuceCase() {
    RedisClient redisClient = RedisClient.create("redis://" + address);
    StatefulRedisConnection<String, String> connection0 = redisClient.connect();
    RedisCommands<String, String> syncCommand = connection0.sync();
    syncCommand.get("key");

    StatefulRedisConnection<String, String> connection1 = redisClient.connect();
    RedisAsyncCommands<String, String> asyncCommands = connection1.async();
    asyncCommands.setAutoFlushCommands(false);
    List<RedisFuture<?>> futures = new ArrayList<>();
    futures.add(asyncCommands.set("key0", "value0"));
    futures.add(asyncCommands.set("key1", "value1"));
    asyncCommands.flushCommands();
    LettuceFutures.awaitAll(5, TimeUnit.SECONDS, futures.toArray(new RedisFuture[futures.size()]));

    connection0.close();
    connection1.close();
    redisClient.shutdown();
    return "Success";
}
 
Example #4
Source File: LettuceSessionClient.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
<T> T async(Function<RedisAsyncCommands<String, Object>, T> s) {
    try (StatefulRedisConnection<String, Object> conn = pool.borrowObject()) {
        return s.apply(conn.async());
    } catch (Exception e) {
        log.error("Failed to borrow a connection", e);
        return null;
    }
}
 
Example #5
Source File: RedisSources.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
HashContext(
        RedisURI uri,
        K hash,
        SupplierEx<RedisCodec<K, V>> codecSupplier,
        FunctionEx<Map.Entry<K, V>, T> mapFn
) {
    this.client = RedisClient.create(uri);
    this.connection = client.connect(codecSupplier.get());

    this.mapFn = mapFn;

    RedisAsyncCommands<K, V> commands = connection.async();
    this.commandFuture = commands.hgetall(this, hash);
}
 
Example #6
Source File: LettuceIntegrationLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenMultipleOperationsThatNeedToBeExecutedAtomically_thenWrapThemInATransaction() throws Exception {

    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();

    // Start a transaction
    asyncCommands.multi();

    // Add three sets to it, and save the future responses
    RedisFuture<String> result1 = asyncCommands.set("key1", "value1");
    RedisFuture<String> result2 = asyncCommands.set("key2", "value2");
    RedisFuture<String> result3 = asyncCommands.set("key3", "value3");

    // Execute it
    RedisFuture<TransactionResult> execResult = asyncCommands.exec();

    TransactionResult transactionResult = execResult.get();

    // Get the three results in the transaction return
    String firstResult = transactionResult.get(0);
    String secondResult = transactionResult.get(0);
    String thirdResult = transactionResult.get(0);

    // Our results are in both!
    assertTrue(firstResult.equals("OK"));
    assertTrue(secondResult.equals("OK"));
    assertTrue(thirdResult.equals("OK"));

    assertTrue(result1.get().equals("OK"));
    assertTrue(result2.get().equals("OK"));
    assertTrue(result3.get().equals("OK"));
}
 
Example #7
Source File: LettuceIntegrationLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenSetElements_thenSaveThemInRedisSetAsync() throws Exception {

    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();

    String countries = "countries";

    String countryOne = "Spain";
    String countryTwo = "Ireland";
    String countryThree = "Ireland";

    asyncCommands.sadd(countries, countryOne);

    RedisFuture<Set<String>> countriesSetFuture = asyncCommands.smembers(countries);
    Assert.assertEquals(2, countriesSetFuture.get().size());

    asyncCommands.sadd(countries, countryTwo);
    countriesSetFuture = asyncCommands.smembers(countries);
    Assert.assertEquals(2, countriesSetFuture.get().size());

    asyncCommands.sadd(countries, countryThree);
    countriesSetFuture = asyncCommands.smembers(countries);
    Assert.assertEquals(2, countriesSetFuture.get().size());

    RedisFuture<Boolean> exists = asyncCommands.sismember(countries, countryThree);
    assertTrue(exists.get());
}
 
Example #8
Source File: LettuceRedisCacheManager.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(Set<CacheKeyTO> keys) {
    // 为了提升性能,开启pipeline
    this.connection.setAutoFlushCommands(false);
    RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
    try {
        for (CacheKeyTO cacheKeyTO : keys) {
            String cacheKey = cacheKeyTO.getCacheKey();
            if (null == cacheKey || cacheKey.isEmpty()) {
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("delete cache {}", cacheKey);
            }
            String hfield = cacheKeyTO.getHfield();
            if (null == hfield || hfield.isEmpty()) {
                asyncCommands.del(KEY_SERIALIZER.serialize(cacheKey));
            } else {
                asyncCommands.hdel(KEY_SERIALIZER.serialize(cacheKey), KEY_SERIALIZER.serialize(hfield));
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        this.connection.flushCommands();
    }
}
 
Example #9
Source File: LettuceRedisCacheManager.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public void mset(Collection<MSetParam> params) {
    // 为了提升性能,开启pipeline
    this.connection.setAutoFlushCommands(false);
    RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
    try {
        LettuceRedisUtil.executeMSet((AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, params);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    } finally {
        this.connection.flushCommands();
    }
}
 
Example #10
Source File: LettuceRedisCacheManager.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
    // 为了提升性能,开启pipeline
    this.connection.setAutoFlushCommands(false);
    RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
    asyncCommands.hset(key, field, value);
    asyncCommands.expire(key, seconds);
    this.connection.flushCommands();
}
 
Example #11
Source File: TracingLettuce51Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #12
Source File: TracingRedisAsyncCommands.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param commands redis async commands
 * @param tracingConfiguration tracing configuration
 */
public TracingRedisAsyncCommands(RedisAsyncCommands<K, V> commands,
    TracingConfiguration tracingConfiguration) {
  this.commands = commands;
  this.tracingConfiguration = tracingConfiguration;
  this.helper = new TracingHelper(tracingConfiguration);
}
 
Example #13
Source File: TracingLettuce50Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #14
Source File: TracingRedisAsyncCommands.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param commands redis async commands
 * @param tracingConfiguration tracing configuration
 */
public TracingRedisAsyncCommands(RedisAsyncCommands<K, V> commands,
    TracingConfiguration tracingConfiguration) {
  this.commands = commands;
  this.tracingConfiguration = tracingConfiguration;
  this.helper = new TracingHelper(tracingConfiguration);
}
 
Example #15
Source File: TracingLettuce52Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #16
Source File: RedisSources.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
SortedSetContext(RedisURI uri, RedisCodec<K, V> codec, K key, long start, long stop) {
    client = RedisClient.create(uri);
    connection = client.connect(codec);

    RedisAsyncCommands<K, V> commands = connection.async();
    commandFuture = commands.zrangebyscoreWithScores(this, key, Range.create(start, stop));
}
 
Example #17
Source File: TracingRedisAsyncCommands.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param commands redis async commands
 * @param tracingConfiguration tracing configuration
 */
public TracingRedisAsyncCommands(RedisAsyncCommands<K, V> commands,
    TracingConfiguration tracingConfiguration) {
  this.commands = commands;
  this.tracingConfiguration = tracingConfiguration;
  this.helper = new TracingHelper(tracingConfiguration);
}
 
Example #18
Source File: Lettuce5InstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncLettuce() throws Exception {
    RedisAsyncCommands<String, String> async = connection.async();
    try (Scope scope = tracer.startRootTransaction(getClass().getClassLoader()).withName("transaction").activateInScope()) {
        async.set("foo", "bar").get();
        assertThat(async.get("foo").get()).isEqualTo("bar");
    }
    assertTransactionWithRedisSpans("SET", "GET");
}
 
Example #19
Source File: Lettuce5InstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchedLettuce() throws Exception {
    RedisAsyncCommands<String, String> async = connection.async();
    try (Scope scope = tracer.startRootTransaction(getClass().getClassLoader()).withName("transaction").activateInScope()) {
        async.set("foo", "bar").get();
        async.setAutoFlushCommands(false);
        List<RedisFuture<String>> futures = List.of(async.get("foo"), async.get("foo"));
        async.flushCommands();
        LettuceFutures.awaitAll(Duration.ofSeconds(5), futures.toArray(new RedisFuture[0]));
    }
    assertTransactionWithRedisSpans("SET", "GET", "GET");
}
 
Example #20
Source File: LettuceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsync(final MockTracer tracer) throws Exception {
  try (final StatefulRedisConnection<String,String> connection = client.connect()) {
    final RedisAsyncCommands<String,String> commands = connection.async();
    assertEquals("OK", commands.set("key2", "value2").get(15, TimeUnit.SECONDS));
    assertEquals("value2", commands.get("key2").get(15, TimeUnit.SECONDS));
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(3, spans.size());
}
 
Example #21
Source File: RedisLettuceStarterTest.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@Test
public void tests() throws Exception {
    if (RedisLettuceCacheTest.checkOS()) {
        System.setProperty("spring.profiles.active", "redislettuce-cluster");
    } else {
        System.setProperty("spring.profiles.active", "redislettuce");
    }
    context = SpringApplication.run(RedisLettuceStarterTest.class);
    doTest();
    A bean = context.getBean(A.class);
    bean.test();

    RedisClient t1 = (RedisClient) context.getBean("defaultClient");
    RedisClient t2 = (RedisClient) context.getBean("a1Client");
    Assert.assertNotNull(t1);
    Assert.assertNotNull(t2);
    Assert.assertNotSame(t1, t2);

    AutoConfigureBeans acb = context.getBean(AutoConfigureBeans.class);

    String key = "remote.A1";
    Assert.assertTrue(new LettuceFactory(acb, key, StatefulRedisConnection.class).getObject() instanceof StatefulRedisConnection);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisCommands.class).getObject() instanceof RedisCommands);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisAsyncCommands.class).getObject() instanceof RedisAsyncCommands);
    Assert.assertTrue(new LettuceFactory(acb, key, RedisReactiveCommands.class).getObject() instanceof RedisReactiveCommands);

    if (RedisLettuceCacheTest.checkOS()) {
        key = "remote.A2";
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterClient.class).getObject() instanceof RedisClusterClient);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterCommands.class).getObject() instanceof RedisClusterCommands);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterAsyncCommands.class).getObject() instanceof RedisClusterAsyncCommands);
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterReactiveCommands.class).getObject() instanceof RedisClusterReactiveCommands);

        key = "remote.A2_slave";
        Assert.assertTrue(new LettuceFactory(acb, key, RedisClusterClient.class).getObject() instanceof RedisClusterClient);
    }
}
 
Example #22
Source File: RedisLettuceCacheTest.java    From jetcache with Apache License 2.0 5 votes vote down vote up
private void testUnwrap(AbstractRedisClient client) {
    Assert.assertTrue(cache.unwrap(AbstractRedisClient.class) instanceof AbstractRedisClient);
    if (client instanceof RedisClient) {
        Assert.assertTrue(cache.unwrap(RedisClient.class) instanceof RedisClient);
        Assert.assertTrue(cache.unwrap(RedisCommands.class) instanceof RedisCommands);
        Assert.assertTrue(cache.unwrap(RedisAsyncCommands.class) instanceof RedisAsyncCommands);
        Assert.assertTrue(cache.unwrap(RedisReactiveCommands.class) instanceof RedisReactiveCommands);
    } else {
        Assert.assertTrue(cache.unwrap(RedisClusterClient.class) instanceof RedisClusterClient);
        Assert.assertTrue(cache.unwrap(RedisClusterCommands.class) instanceof RedisClusterCommands);
        Assert.assertTrue(cache.unwrap(RedisClusterAsyncCommands.class) instanceof RedisClusterAsyncCommands);
        Assert.assertTrue(cache.unwrap(RedisClusterReactiveCommands.class) instanceof RedisClusterReactiveCommands);
    }
}
 
Example #23
Source File: RedisLettuceCacheFailTest.java    From jetcache with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() {
    client = mock(RedisClient.class);
    StatefulRedisConnection connection = mock(StatefulRedisConnection.class);
    asyncCommands = mock(RedisAsyncCommands.class);
    when(client.connect((JetCacheCodec) any())).thenReturn(connection);
    when(connection.sync()).thenReturn(null);
    when(connection.async()).thenReturn(asyncCommands);

    cache = RedisLettuceCacheBuilder.createRedisLettuceCacheBuilder()
            .redisClient(client)
            .keyPrefix("fail_test")
            .buildCache();
}
 
Example #24
Source File: WrapperTests.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAsyncCommandsImplCallsWrapperFunctions() {
    @SuppressWarnings("unchecked")
    RedisAsyncCommands<String, String> wrapped = (RedisAsyncCommands<String, String>)
            mock(RedisAsyncCommands.class);
    AsyncCommands<String> cmd = new AsyncCommandsImpl<>(wrapped);
    cmd.setAutoFlushCommands(true);
    verify(wrapped, ONCE).setAutoFlushCommands(true);
    cmd.flushCommands();
    verify(wrapped).flushCommands();
    cmd.keys("pattern:*");
    verify(wrapped).keys("pattern:*");
    cmd.get("key");
    verify(wrapped).get("key");
    cmd.incr("key");
    verify(wrapped).incr("key");
    cmd.sadd("key", "v1", "v2", "v3");
    verify(wrapped).sadd("key", "v1", "v2", "v3");
    cmd.srem("key", "v1", "v2");
    verify(wrapped).srem("key", "v1", "v2");
    cmd.del("key1", "key2");
    verify(wrapped).del("key1", "key2");
    cmd.smembers("key");
    verify(wrapped).smembers("key");
    @SuppressWarnings("unchecked")
    Map<String, String> mockMap = (Map<String, String>) mock(Map.class);
    cmd.hmset("key", mockMap);
    verify(wrapped).hmset("key", mockMap);
    cmd.hgetall("key");
    verify(wrapped).hgetall("key");
    ScoredValue<String> sv1 = ScoredValue.fromNullable(1.0, "12");
    ScoredValue<String> sv2 = ScoredValue.fromNullable(1.2, "13");
    cmd.zadd("key", sv1, sv2);
    verify(wrapped).zadd("key", sv1, sv2);
    cmd.zrangeWithScores("key", 1, 100);
    verify(wrapped).zrangeWithScores("key", 1, 100);
}
 
Example #25
Source File: LettuceIntegrationLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenMultipleIndependentOperations_whenNetworkOptimizationIsImportant_thenFlushManually() throws Exception {

    int iterations = 50;

    RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();

    asyncCommands.setAutoFlushCommands(false);

    List<RedisFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < iterations; i++) {
        futures.add(asyncCommands.set("key" + i, "value" + i));
    }

    asyncCommands.flushCommands();

    // Wait until all futures complete
    boolean result = LettuceFutures.awaitAll(5, TimeUnit.SECONDS, futures.toArray(new RedisFuture[futures.size()]));

    asyncCommands.setAutoFlushCommands(true);

}
 
Example #26
Source File: RedisSinks.java    From hazelcast-jet-contrib with Apache License 2.0 4 votes vote down vote up
void add(T item) {
    RedisAsyncCommands<K, V> async = connection.async();
    Map<K, V> body = mapFn.apply(item);
    RedisFuture<String> future = async.xadd(stream, body);
    futures.add(future);
}
 
Example #27
Source File: LettuceRedisCacheManager.java    From AutoLoadCache with Apache License 2.0 4 votes vote down vote up
@Override
public Map<CacheKeyTO, CacheWrapper<Object>> mget(Type returnType, Set<CacheKeyTO> keys) {
    RedisAsyncCommands<byte[], byte[]> asyncCommands = connection.async();
    return LettuceRedisUtil.executeMGet(connection, (AbstractRedisAsyncCommands<byte[], byte[]>) asyncCommands, cacheManager, returnType, keys);
}
 
Example #28
Source File: AsyncCommandsImpl.java    From sherlock with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param commands Redis commands to wrap
 */
protected AsyncCommandsImpl(RedisAsyncCommands<K, K> commands) {
    this.commands = commands;
}
 
Example #29
Source File: TracingLettuce51Test.java    From java-redis-client with Apache License 2.0 4 votes vote down vote up
@Test
public void async() throws Exception {
  RedisClient client = RedisClient.create("redis://localhost");

  StatefulRedisConnection<String, String> connection =
      new TracingStatefulRedisConnection<>(client.connect(),
          new TracingConfiguration.Builder(mockTracer).build());

  RedisAsyncCommands<String, String> commands = connection.async();

  assertEquals("OK", commands.set("key2", "value2").get(15, TimeUnit.SECONDS));

  assertEquals("value2", commands.get("key2").get(15, TimeUnit.SECONDS));

  connection.close();

  client.shutdown();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #30
Source File: TracingStatefulRedisConnection.java    From java-redis-client with Apache License 2.0 4 votes vote down vote up
@Override
public RedisAsyncCommands<K, V> async() {
  return new TracingRedisAsyncCommands<>(connection.async(), tracingConfiguration);
}