我想删除所有密钥。我要把一切都删掉,给我一个空白的数据库。

有没有办法在Redis客户端中做到这一点?


当前回答

您可以在python中使用以下方法

def redis_clear_cache(self):

    try:
        redis_keys = self.redis_client.keys('*')
    except Exception as e:
        # print('redis_client.keys() raised exception => ' + str(e))
        return 1

    try:
        if len(redis_keys) != 0:
            self.redis_client.delete(*redis_keys)
    except Exception as e:
        # print('redis_client.delete() raised exception => ' + str(e))
        return 1

    # print("cleared cache")
    return 0

其他回答

警惕FLUSHOLL可能过度使用。FLUSHDB仅用于刷新数据库。FLUSHOLL将清除整个服务器。就像服务器上的每个数据库一样。由于问题是关于刷新数据库,我认为这是一个足够重要的区别,值得单独回答。

使用redis cli:

FLUSHDB–从连接的当前数据库中删除所有密钥。FLUSHOLL–从所有数据库中删除所有密钥。

例如,在shell中:

redis-cli flushall

使用以下命令启动Redis服务器后:service Redis server start--port 8000或Redis server。

使用redis cli-p 8000在不同的终端中作为客户端连接到服务器。

您可以使用

FLUSHDB-删除当前选定DB的所有键。此命令从未失败。此操作的时间复杂度为O(N),N是数据库中的密钥数。FLUSHOLL-删除所有现有数据库的所有键,而不仅仅是当前选定的键。此命令从未失败。此操作的时间复杂度为O(N),N是所有现有数据库中的密钥数。

检查ASYNC选项的文档。

如果您通过其python接口使用Redis,请使用以下两个函数实现相同的功能:

def flushall(self):
    "Delete all keys in all databases on the current host"
    return self.execute_command('FLUSHALL')

and

def flushdb(self):
    "Delete all keys in the current database"
    return self.execute_command('FLUSHDB')

您可以使用FLUSHOLL从每个数据库中删除所有密钥。其中,FLUSHDB将删除当前数据库中的所有密钥。

如果您使用的是Java,那么从文档中可以根据您的用例使用其中的任何一个。

/**
 * Remove all keys from all databases.
 *
 * @return String simple-string-reply
 */
String flushall();

/**
 * Remove all keys asynchronously from all databases.
 *
 * @return String simple-string-reply
 */
String flushallAsync();

/**
 * Remove all keys from the current database.
 *
 * @return String simple-string-reply
 */
String flushdb();

/**
 * Remove all keys asynchronously from the current database.
 *
 * @return String simple-string-reply
 */
String flushdbAsync();

代码:

RedisAdvancedClusterCommands syncCommands = // get sync() or async() commands 
syncCommands.flushdb();

阅读更多信息:https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster