How to get all Keys from Redis using redis template

后端 未结 7 1239
误落风尘
误落风尘 2020-12-31 06:30

I have been stuck with this problem with quite some time.I want to get keys from redis using redis template. I tried this.redistemplate.keys(\"*\"); but this doesn\'t fetch

7条回答
  •  一向
    一向 (楼主)
    2020-12-31 07:00

    Avoid to use keys command. It may ruin performance when it is executed against large databases.

    You should use scan command instead. Here is how you can do it:

    RedisConnection redisConnection = null;
    try {
        redisConnection = redisTemplate.getConnectionFactory().getConnection();
        ScanOptions options = ScanOptions.scanOptions().match("myKey*").count(100).build();
    
        Cursor c = redisConnection.scan(options);
        while (c.hasNext()) {
            logger.info(new String((byte[]) c.next()));
        }
    } finally {
        redisConnection.close(); //Ensure closing this connection.
    }
    

    or do it much simplier with Redisson Redis Java client:

    Iterable keysIterator = redisson.getKeys().getKeysByPattern("test*", 100);
    for (String key : keysIterator) {
        logger.info(key);
    }
    

提交回复
热议问题