io.lettuce.core.LettuceFutures Java Examples

The following examples show how to use io.lettuce.core.LettuceFutures. 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: 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 #2
Source File: RedisSinks.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
void flush() {
    boolean flushed = LettuceFutures.awaitAll(FLUSH_TIMEOUT, futures.toArray(new RedisFuture[0]));
    if (!flushed) {
        throw new RuntimeException("Flushing failed!");
    }
    futures.clear();
}
 
Example #3
Source File: RedisSinks.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
void flush() {
    boolean flushed = LettuceFutures.awaitAll(FLUSH_TIMEOUT, futures.toArray(new RedisFuture[0]));
    if (!flushed) {
        throw new RuntimeException("Flushing failed!");
    }
    futures.clear();
}
 
Example #4
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 #5
Source File: RedisStandaloneIngestionClient.java    From feast with Apache License 2.0 5 votes vote down vote up
@Override
public void sync() {
  // Wait for some time for futures to complete
  // TODO: should this be configurable?
  try {
    LettuceFutures.awaitAll(60, TimeUnit.SECONDS, futures.toArray(new RedisFuture[0]));
  } finally {
    futures.clear();
  }
}
 
Example #6
Source File: RedisClusterIngestionClient.java    From feast with Apache License 2.0 5 votes vote down vote up
@Override
public void sync() {
  try {
    LettuceFutures.awaitAll(60, TimeUnit.SECONDS, futures.toArray(new RedisFuture[0]));
  } finally {
    futures.clear();
  }
}
 
Example #7
Source File: RedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return the given key, if it is not expired.
 * 
 * Time Complexity is 2*O(1).
 */
@Override
public cfData get( String key ) {
	try {
		// Calculate the time now, represented as a decimal
		long nowSecs = Instant.now().getMillis() / 1000;
		double nowTtl = getDecimalTtl( nowSecs );

		List<RedisFuture<?>> futures = new ArrayList<RedisFuture<?>>();

		RedisFuture<Double> zscoreFuture = asyncCommands.zscore( ttls, key ); // Time complexity: O(1);
		futures.add(zscoreFuture); 
		
		RedisFuture<String> hgetFuture = asyncCommands.hget( region, key ); // Time complexity: O(1);
		futures.add(hgetFuture); 
		
		/* Wait until futures are complete or the supplied timeout is reached. 
		 * Commands are not cancelled (in contrast to awaitOrCancel(RedisFuture, long, TimeUnit)) when the timeout expires.
		 */
		boolean allDone = LettuceFutures.awaitAll(Duration.ofSeconds(waitTimeSeconds), futures.toArray(new RedisFuture[futures.size()]));
		
		String base64value = null;
		if(allDone) {
			// Get the result of the 'ZSCORE' command, the TTL for the given key
			Double keyTtl = zscoreFuture.get();
			if ( keyTtl != null && keyTtl > nowTtl ) {
				// Set the value to be returned, when the TTL is not expired
				base64value = hgetFuture.get();
			}
		}
		
		// cfEngine.log( logPrefix  + " GET returned " + (base64value == null ? 0 : base64value.length()) );
		
		return base64value == null ? null : (cfData) Transcoder.fromString( base64value );


	} catch ( Exception e ) {
		cfEngine.log( logPrefix  + " get failed:\n" + ExceptionUtils.getStackTrace(e));
		return null;
	}
}
 
Example #8
Source File: RedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns all the keys belonging to the region of this cache instance.
 * 
 * Time Complexity is O(N) where N is the number of keys in this region.
 */
@Override
public cfArrayData getAllIds() {

	try {
		
		RedisFuture<List<String>> hkeysFuture = asyncCommands.hkeys( region ); // Time complexity: O(N) where N is the size of the hash.
		List<String> keys = LettuceFutures.awaitOrCancel(hkeysFuture, waitTimeSeconds, TimeUnit.SECONDS);
		
		// cfEngine.log( logPrefix  + " >> getAllIds returned " + (keys == null ? 0 : keys.size() ) );

		return buildCfArrayData( keys );

	} catch ( Exception e ) {
		cfEngine.log( logPrefix  + " >> getAllIds Failed:\n" + ExceptionUtils.getStackTrace(e));
	}

	return null;

}
 
Example #9
Source File: RedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Set the given key and value in the region for this cache instance,
 * with the given time-to-live, i.e. ageMS.
 * 
 * Time Complexity is O(1) to set the key-value pair and O(log(N) to set the tll for the key,
 * where N is the number of the keys in this region.
 * 
 * @param key
 *          the given key.
 * @param data
 *          the value for this key.
 * @param ageMS
 *          the ttl for this key-value pair. If ageMS < 1 || ageMs > dayMs, then ageMS = dayMs.
 * @param idleTime
 *          not used in this implementation.
 */
@SuppressWarnings("unused")
@Override
public void set( String key, cfData data, long ageMS, long idleTime ) {

	try {
		
		// Convert the ageMs, tll in milliseconds, to ageSecs, ttl in seconds.
		long ageSecs;
		if ( ageMS < 1 || ageMS > DAY_MS ) {
			ageSecs = DAY_MS / 1000;
		} else {
			ageSecs = ageMS / 1000;
		}

		// Get the time now in seconds plus the ageSecs in seconds
		long nowSecs = Instant.now().getMillis() / 1000 + ageSecs;

		// Convert the time now in seconds to a decimal
		double ttl = getDecimalTtl( nowSecs );

		LettuceAssert.notNull(key, "'key' cannot be null");
		LettuceAssert.notNull(data, "'data' cannot be null" );

		String base64value = Transcoder.toString( data );
					
		RedisFuture<Boolean> futureHset = asyncCommands.hset( region, key, base64value ); // Time complexity: O(1)
		RedisFuture<Long> futureZadd = asyncCommands.zadd( ttls, ttl, key ); // O(log(N)) for each key added, where N is the number of keys in the sorted set.
		
		List<RedisFuture<?>> futures = new ArrayList<RedisFuture<?>>();
		futures.add(futureHset); 
		futures.add(futureZadd); 

		/* Wait until futures are complete or the supplied timeout is reached. 
		 * Commands are not cancelled (in contrast to awaitOrCancel(RedisFuture, long, TimeUnit)) when the timeout expires.
		 */
		LettuceFutures.awaitAll(Duration.ofSeconds(waitTimeSeconds), futures.toArray(new RedisFuture[futures.size()]));

	} catch ( Exception e ) {
		cfEngine.log( logPrefix  + " >> set Failed:\n" + ExceptionUtils.getStackTrace(e));
	}
}
 
Example #10
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 #11
Source File: AbstractLettuceAccessor.java    From sherlock with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Await an array of futures.
 *
 * @param futures redis futures to await
 */
protected void await(RedisFuture... futures) {
    LettuceFutures.awaitAll(timeoutMillis, TimeUnit.MILLISECONDS, futures);
}