Java Code Examples for io.lettuce.core.RedisFuture#get()

The following examples show how to use io.lettuce.core.RedisFuture#get() . 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: LettuceJobMetadataAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String saveRedisJobsMetadata() throws IOException {
    log.info("Saving redis snapshot");
    String response;
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<String> res = cmd.bgsave();
        cmd.flushCommands();
        await(res);
        response = res.get();
        log.info("Status: " + response);
    } catch (ExecutionException | InterruptedException e) {
        log.error("Exception while running BGSAVE", e);
        throw new IOException(e.getMessage(), e);
    }
    return response;
}
 
Example 3
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object send(String[] params) {
    // 同步异步均需返回结果
    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commandAsync = connect.async();
    RedisFuture<String> result = commandAsync.lindex(params[0], Long.parseLong(params[1]));
    String res = "";
    try {
        res = result.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setRunState(false);
    }
    lcr.setResult(res);
    return lcr;
}
 
Example 4
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object send(String[] params) {
    // 同步异步都要求返回结果

    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commandAsync = connect.async();
    try {
        RedisFuture<Long> result = commandAsync.lrem(params[0], Long.parseLong(params[1]), params[2]);
        long res = result.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setResult((int) res);
        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setResult(0);
        lcr.setRunState(false);
    }
    return lcr;
}
 
Example 5
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object send(String[] params) {
    // 无论同步异步都要求返回结果
    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commandAsync = connect.async();
    RedisFuture<String> result = commandAsync.rpop(params[0]);
    try {
        String res = result.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setResult(res);
        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setRunState(false);
    }
    return lcr;
}
 
Example 6
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object send(String[] params) {
    // 只有异步
    Map<String, String> mapValues = new HashMap<String, String>();
    for (int i = 1; i < params.length; i++) {
        mapValues.put(params[i].toString(), params[i + 1].toString());
        i++;
    }
    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commands = connect.async();

    try {
        RedisFuture<String> result = commands.hmset(params[0], mapValues);
        String res = result.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setResult(result);
        lcr.setRunState(res.equals("OK"));
    }
    catch (Exception e) {
        lcr.setRunState(false);
    }
    return lcr;
}
 
Example 7
Source File: LettuceDruidClusterAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void deleteDruidCluster(String clusterId) throws IOException, ClusterNotFoundException {
    log.info("Deleting Druid cluster [{}]", clusterId);
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Long> sremRes = cmd.srem(index(clusterIdName, "all"), clusterId);
        RedisFuture<Long> delRes = cmd.del(key(clusterId));
        cmd.flushCommands();
        await(sremRes, delRes);
        if (delRes.get() == 0) {
            throw new ClusterNotFoundException(clusterId);
        }
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error while deleting Druid cluster!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 8
Source File: LettuceAnomalyReportAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<AnomalyReport> getAnomalyReportsForJob(String jobId, String frequency) throws IOException {
    log.info("Getting anomaly reports for job [{}] with frequency [{}]", jobId, frequency);
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> jobReportIds = cmd.smembers(index(jobIdName, jobId));
        RedisFuture<Set<String>> freqReportIds = cmd.smembers(index(frequencyName, frequency));
        cmd.flushCommands();
        await(jobReportIds, freqReportIds);
        Set<String> reportIds = jobReportIds.get();
        reportIds.retainAll(freqReportIds.get());
        return getAnomalyReports(reportIds, this);
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while getting anomaly reports!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 9
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object send(String[] params) {
    // 同步异步都需要返回结果
    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commands = connect.async();
    RedisFuture<String> resultSync = commands.get(params[0]);
    String result = null;
    try {
        result = resultSync.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setResult(result);
        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setRunState(false);
    }

    return lcr;
}
 
Example 10
Source File: LettuceEmailMetadataAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<String> checkEmailsInInstantIndex(List<String> emails) throws IOException {
    log.info("Checking for emails in Instant index");
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> future = cmd.smembers(index(emailTriggerIndex, Triggers.INSTANT.toString()));
        cmd.flushCommands();
        await(future);
        List<String> result = new ArrayList<>();
        Set<String> instantList = future.get();
        for (String email : emails) {
            if (instantList.contains(email)) {
                result.add(email);
            }
        }
        return result;
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while getting instant email index!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 11
Source File: LettuceEmailMetadataAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void putEmailMetadataIfNotExist(String emailId, String jobId) throws IOException {
    log.info("Putting Email with ID [{}] if not already exist", emailId);
    try (RedisConnection<String> conn = connect()) {
        if (emailId != null) {
            AsyncCommands<String> cmd = conn.async();
            cmd.setAutoFlushCommands(false);
            RedisFuture<Long> checkIndex = cmd.sadd(index(emailIdIndex, DatabaseConstants.EMAILS), emailId);
            RedisFuture<Long> jobEmailIndex = cmd.sadd(index(emailJobIndex, emailId), jobId);
            cmd.flushCommands();
            await(checkIndex, jobEmailIndex);
            if (checkIndex.get() != 0L) {
                putEmailMetadata(new EmailMetaData(emailId));
            } else {
                log.info("[{}] already exist", emailId);
            }
        } else {
            log.error("Email ID can not be null!");
        }
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while deleting job!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 12
Source File: LettuceAnomalyReportAccessor.java    From sherlock with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<AnomalyReport> getAnomalyReportsForJobAtTime(String jobId, String time, String frequency) throws IOException {
    log.info("Getting anomaly reports for job [{}] frequency [{}] at time [{}]", jobId, frequency, time);
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> jobRepIds = cmd.smembers(index(jobIdName, jobId));
        RedisFuture<Set<String>> jobTimeIds = cmd.smembers(index(timeName, time));
        RedisFuture<Set<String>> jobFreqIds = cmd.smembers(index(frequencyName, frequency));
        cmd.flushCommands();
        await(jobRepIds, jobTimeIds, jobFreqIds);
        Set<String> reportIds = jobRepIds.get();
        reportIds.retainAll(jobTimeIds.get());
        reportIds.retainAll(jobFreqIds.get());
        return getAnomalyReports(reportIds, this);
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while getting anomaly reports!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 13
Source File: SessionStorageRedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onRequestStart( cfSession Session, long sessionTimeOut, sessionUtility sessionInfo ) {
	boolean sessionStart = false;
	cfSessionData sessData = null;

	// If the timeout is greater than 0, then lookup it from Redis
	if ( sessionTimeOut > 0 ) {
		RedisFuture<String> future = null;

		try {

			future = asyncCommands.get( appName + sessionInfo.getTokenShort() );

			String obj = future.get( 3, TimeUnit.SECONDS );

			sessData = obj == null ? null : (cfSessionData) Transcoder.fromString( obj );

		} catch ( Exception e ) {
			cfEngine.log( "SessionStorageRedisCache get Failed: " + e.getMessage() );
			future.cancel( false );
		}

	}

	if ( sessData == null ) {
		sessData = new cfSessionData( appName );
		sessionStart = true;
	}

	sessData.setSessionID( appName, sessionInfo.CFID, sessionInfo.CFTOKEN );
	sessData.setTimeOut( sessionTimeOut );
	Session.setQualifiedData( variableStore.SESSION_SCOPE, sessData );


	return sessionStart;
}
 
Example 14
Source File: LettuceEmailMetadataAccessor.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<EmailMetaData> getAllEmailMetadata() throws IOException {
    log.info("Getting metadata for all emails");
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> emailFutureList = cmd.smembers(index(emailIdIndex, DatabaseConstants.EMAILS));
        cmd.flushCommands();
        await(emailFutureList);
        Set<String> emailList = emailFutureList.get();
        List<RedisFuture<Map<String, String>>> values = new ArrayList<>(emailList.size());
        log.info("Fetching metadata for {} emails", emailList.size());
        for (String emailId : emailList) {
            values.add(cmd.hgetall(key(emailId)));
        }
        cmd.flushCommands();
        await(values);
        List<EmailMetaData> emailMetaDataList = new ArrayList<>(values.size());
        for (RedisFuture<Map<String, String>> value : values) {
            emailMetaDataList.add(unmap(EmailMetaData.class, value.get()));
        }
        return emailMetaDataList;
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while getting emails metadata!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 15
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@Override
public Object send(String[] params) {
    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commandAsync = connect.async();
    RedisFuture<Map<String, String>> result = commandAsync.hgetall(params[0]);
    try {
        Map<String, String> res = result.get(expireTimeLong, TimeUnit.SECONDS);
        lcr.setResult(res);
        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setRunState(false);
    }
    return lcr;
}
 
Example 16
Source File: LettuceAsyncService.java    From uavstack with Apache License 2.0 5 votes vote down vote up
@Override
public Object send(String[] params) {
    // 同步异步均需要返回结果

    LettuceCommandResult lcr = new LettuceCommandResult();
    RedisAdvancedClusterAsyncCommands<String, String> commandAsync = connect.async();

    RedisFuture<List<String>> result = commandAsync.lrange(params[0], Long.parseLong(params[1]),
            Long.parseLong(params[2]));

    try {
        List<String> res = result.get(expireTimeLong, TimeUnit.SECONDS);

        if (res == null || res.isEmpty()) {
            lcr.setResult(null);
        }
        else {
            String[] resultArray = new String[res.size()];
            for (int i = 0; i < res.size(); i++) {
                resultArray[i] = res.get(i).toString();
            }
            lcr.setResult(resultArray);
        }

        lcr.setRunState(true);
    }
    catch (Exception e) {
        lcr.setResult(Collections.emptyList());
        lcr.setRunState(false);
    }
    return lcr;
}
 
Example 17
Source File: RedisCacheImpl.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns general statistics about the server.
 * This is the content of section 'stats' in Redis command 'INFO'.
 * 
 * (see https://redis.io/commands/info)
 */
@Override
public cfStructData getStats() {
	cfStructData stats = new cfStructData();

	RedisFuture<String> future = null;

	try {
		// Get the INFO stats information
		future = asyncCommands.info( "stats" );
		Object obj = future.get( waitTimeSeconds, TimeUnit.SECONDS );

		if ( obj == null )
			return null;
		else if ( obj instanceof String ) {
			// Parse the result of INFO stats in order to build a cfStructData carrying the results
			BufferedReader reader = new BufferedReader( new StringReader( obj.toString() ) );
			String line;
			while ( ( line = reader.readLine() ) != null ) {
				String[] keyValue = line.split( ":" );
				if ( keyValue.length == 2 ) {
					stats.setData( keyValue[0], new cfStringData( keyValue[1] ) );
				}
			}

		}

	} catch ( Exception e ) {
		cfEngine.log( logPrefix  + " getStats failed:\n" + ExceptionUtils.getStackTrace(e));
		
		if ( future != null ) {
			future.cancel( false );
		}
	}

	return stats;
}
 
Example 18
Source File: LettuceAnomalyReportAccessor.java    From sherlock with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<AnomalyReport> getAnomalyReportsForEmailId(String emailId) throws IOException {
    log.info("Getting anomaly reports for Email ID [{}]", emailId);
    try (RedisConnection<String> conn = connect()) {
        AsyncCommands<String> cmd = conn.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> emailReportIds = cmd.smembers(index(emailIdReportName, emailId));
        cmd.flushCommands();
        await(emailReportIds);
        Set<String> reportIds = emailReportIds.get();
        String[] rarr = new String[reportIds.size()];
        int i = 0;
        for (String s : reportIds) {
            rarr[i] = s; i++;
        }
        if (i > 0) {
            RedisFuture<Long> removedReports = cmd.srem(index(emailIdReportName, emailId), rarr);
            cmd.flushCommands();
            await(removedReports);
        }
        log.info("Removed {} anomaly reports to send it to {}", rarr.length, emailId);
        return getAnomalyReports(reportIds, this);
    } catch (Exception e) {
        log.error("Error occurred while getting anomaly reports!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 19
Source File: LettuceAnomalyReportAccessor.java    From sherlock with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void deleteAnomalyReportsForJobAtTime(String jobId, String time, String frequency) throws IOException {
    log.info("Getting anomaly reports for job [{}] frequency [{}] at time [{}] for deletion", jobId, frequency, time);
    try (
        RedisConnection<String> conn = connect();
        RedisConnection<byte[]> binary = binary()
    ) {
        // Get all report IDs
        AsyncCommands<String> cmd = conn.async();
        AsyncCommands<byte[]> bin = binary.async();
        cmd.setAutoFlushCommands(false);
        RedisFuture<Set<String>> jobRepIds = cmd.smembers(index(jobIdName, jobId));
        RedisFuture<Set<String>> jobTimeIds = cmd.smembers(index(timeName, time));
        RedisFuture<Set<String>> jobFreqIds = cmd.smembers(index(frequencyName, frequency));
        cmd.flushCommands();
        await(jobRepIds, jobTimeIds, jobFreqIds);
        Set<String> reportIds = jobRepIds.get();
        reportIds.retainAll(jobTimeIds.get());
        reportIds.retainAll(jobFreqIds.get());
        // Delete the reports
        cmd.setAutoFlushCommands(false);
        bin.setAutoFlushCommands(false);
        List<AnomalyReport> reports = getAnomalyReports(reportIds, this);
        RedisFuture[] futures = new RedisFuture[6 * reports.size()];
        int i = 0;
        for (AnomalyReport report : reports) {
            futures[i++] = cmd.srem(index(jobIdName, report.getJobId()), report.getUniqueId());
            futures[i++] = cmd.srem(index(timeName, report.getReportQueryEndTime()), report.getUniqueId());
            futures[i++] = cmd.srem(index(frequencyName, report.getJobFrequency()), report.getUniqueId());
            futures[i++] = cmd.del(key(report.getUniqueId()));
            futures[i++] = bin.del(encode(key(report.getUniqueId(), DatabaseConstants.ANOMALY_TIMESTAMP, "start")));
            futures[i++] = bin.del(encode(key(report.getUniqueId(), DatabaseConstants.ANOMALY_TIMESTAMP, "end")));
        }
        cmd.flushCommands();
        bin.flushCommands();
        await(futures);
    } catch (InterruptedException | ExecutionException e) {
        log.error("Error occurred while deleting anomaly reports!", e);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 20
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;
	}
}