0%

redis-cmd

CMD DESC
APPEND key value 追加一个值到key上
AUTH password 验证服务器命令
BGREWRITEAOF 异步重写追加文件命令
BGSAVE 异步保存数据集到磁盘上
BITCOUNT key [start end] 统计字符串指定起始位置的字节数
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP SAT
BITOP operation destkey key [key …] Perform bitwise operations between strings
BITPOS key bit [start] [end] Find first bit set or clear in a string
BLPOP key [key …] timeout 删除, 并获得该列表中的第一元素, 或阻塞, 直到有一个可用
BRPOP key [key …] timeout 删除, 并获得该列表中的最后一个元素, 或阻塞, 直到有一个可用
BRPOPLPUSH source destination timeout 弹出一个列表的值, 将它推到另一个列表, 并返回它;或阻塞, 直到有一个可用
BZPOPMAX key [key …] timeout Remove and return the member with the highest score from one or more sorted sets, or block until one is available
BZPOPMIN key [key …] timeout Remove and return the member with the lowest score from one or more sorted sets, or block until one is available
CLIENT KILL [ip:port] [ID client-id] [TYPE normal slave
CLIENT LIST 获得客户端连接列表
CLIENT GETNAME 获得当前连接名称
CLIENT ID Returns the client ID for the current connection
CLIENT PAUSE timeout 暂停处理客户端命令
CLIENT REPLY ON OFF
CLIENT SETNAME connection-name 设置当前连接的名字
CLIENT UNBLOCK client-id [TIMEOUT ERROR]
CLUSTER ADDSLOTS slot [slot …] Assign new hash slots to receiving node
CLUSTER COUNT-FAILURE-REPORTS node-id Return the number of failure reports active for a given node
CLUSTER COUNTKEYSINSLOT slot Return the number of local keys in the specified hash slot
CLUSTER DELSLOTS slot [slot …] Set hash slots as unbound in receiving node
CLUSTER FAILOVER [FORCE TAKEOVER]
CLUSTER FORGET node-id Remove a node from the nodes table
CLUSTER GETKEYSINSLOT slot count Return local key names in the specified hash slot
CLUSTER INFO Provides info about Redis Cluster node state
CLUSTER KEYSLOT key Returns the hash slot of the specified key
CLUSTER MEET ip port Force a node cluster to handshake with another node
CLUSTER NODES Get Cluster config for the node
CLUSTER REPLICAS node-id List replica nodes of the specified master node
CLUSTER REPLICATE node-id Reconfigure a node as a slave of the specified master node
CLUSTER RESET [HARD SOFT]
CLUSTER SAVECONFIG Forces the node to save cluster state on disk
CLUSTER SET-CONFIG-EPOCH config-epoch Set the configuration epoch in a new node
CLUSTER SETSLOT slot IMPORTING MIGRATING
CLUSTER SLAVES node-id List slave nodes of the specified master node
CLUSTER SLOTS Get array of Cluster slot to node mappings
COMMAND Get array of Redis command details
COMMAND COUNT Get total number of Redis commands
COMMAND GETKEYS Extract keys given a full Redis command
COMMAND INFO command-name [command-name …] Get array of specific Redis command details
CONFIG GET parameter 获取配置参数的值
CONFIG REWRITE 从写内存中的配置文件
CONFIG SET parameter value 设置配置文件
CONFIG RESETSTAT 复位再分配使用info命令报告的统计
DBSIZE 返回当前数据库里面的keys数量
DEBUG OBJECT key 获取一个key的debug信息
DEBUG SEGFAULT 使服务器崩溃命令
DECR key 整数原子减1
DECRBY key decrement 原子减指定的整数
DEL key [key …] 删除指定的key (一个或多个)
DISCARD 丢弃所有 MULTI 之后发的命令
DUMP key 导出key的值
ECHO message 回显输入的字符串
EVAL script numkeys key [key …] arg [arg …] 在服务器端执行 LUA 脚本
EVALSHA sha1 numkeys key [key …] arg [arg …] 在服务器端执行 LUA 脚本
EXEC 执行所有 MULTI 之后发的命令
EXISTS key [key …] 查询一个key是否存在
EXPIRE key seconds 设置一个key的过期的秒数
EXPIREAT key timestamp 设置一个UNIX时间戳的过期时间
FLUSHALL 清空所有数据库命令
FLUSHDB 清空当前的数据库命令
GEOADD key longitude latitude member [longitude latitude member …] 添加一个或多个地理空间位置到sorted set
GEOHASH key member [member …] 返回一个标准的地理空间的Geohash字符串
GEOPOS key member [member …] 返回地理空间的经纬度
GEODIST key member1 member2 [unit] 返回两个地理空间之间的距离
GEORADIUS key longitude latitude radius m km
GEORADIUSBYMEMBER key member radius m km
GET key 返回key的value
GETBIT key offset 返回位的值存储在关键的字符串值的偏移量.
GETRANGE key start end 获取存储在key上的值的一个子字符串
GETSET key value 设置一个key的value, 并获取设置前的值
HDEL key field [field …] 删除一个或多个Hash的field
HEXISTS key field 判断field是否存在于hash中
HGET key field 获取hash中field的值
HGETALL key 从hash中读取全部的域和值
HINCRBY key field increment 将hash中指定域的值增加给定的数字
HINCRBYFLOAT key field increment 将hash中指定域的值增加给定的浮点数
HKEYS key 获取hash的所有字段
HLEN key 获取hash里所有字段的数量
HMGET key field [field …] 获取hash里面指定字段的值
HMSET key field value [field value …] 设置hash字段值
HSET key field value 设置hash里面一个字段的值
HSETNX key field value 设置hash的一个字段, 只有当这个字段不存在时有效
HSTRLEN key field 获取hash里面指定field的长度
HVALS key 获得hash的所有值
INCR key 执行原子加1操作
INCRBY key increment 执行原子增加一个整数
INCRBYFLOAT key increment 执行原子增加一个浮点数
INFO [section] 获得服务器的详细信息
KEYS pattern 查找所有匹配给定的模式的键
LASTSAVE 获得最后一次同步磁盘的时间
LINDEX key index 获取一个元素, 通过其索引列表
LINSERT key BEFORE AFTER pivot value
LLEN key 获得队列(List)的长度
LPOP key 从队列的左边出队一个元素
LPUSH key value [value …] 从队列的左边入队一个或多个元素
LPUSHX key value 当队列存在时, 从队到左边入队一个元素
LRANGE key start stop 从列表中获取指定返回的元素
LREM key count value 从列表中删除元素
LSET key index value 设置队列里面一个元素的值
LTRIM key start stop 修剪到指定范围内的清单
MEMORY DOCTOR Outputs memory problems report
MEMORY HELP Show helpful text about the different subcommands
MEMORY-MALLOC-STATS Show allocator internal stats
MEMORY-PURGE Ask the allocator to release memory
MEMORY-STATS Show memory usage details
MEMORY-USAGE key [SAMPLES count] Estimate the memory usage of a key
MGET key [key …] 获得所有key的值
MIGRATE host port key destination-db timeout [COPY] [REPLACE] 原子性的将key从redis的一个实例移到另一个实例
MONITOR 实时监控服务器
MOVE key db 移动一个key到另一个数据库
MSET key value [key value …] 设置多个key value
MSETNX key value [key value …] 设置多个key value,仅当key存在时
MULTI 标记一个事务块开始
OBJECT subcommand [arguments [arguments …]] 检查内部的再分配对象
PERSIST key 移除key的过期时间
PEXPIRE key milliseconds 设置key的有效时间以毫秒为单位
PEXPIREAT key milliseconds-timestamp 设置key的到期UNIX时间戳以毫秒为单位
PFADD key element [element …] 将指定元素添加到HyperLogLog
PFCOUNT key [key …] Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
PFMERGE destkey sourcekey [sourcekey …] Merge N different HyperLogLogs into a single one.
PING Ping 服务器
PSETEX key milliseconds value Set the value and expiration in milliseconds of a key
PSUBSCRIBE pattern [pattern …] Listen for messages published to channels matching the given patterns
PUBSUB subcommand [argument [argument …]] Inspect the state of the Pub/Sub subsystem
PTTL key 获取key的有效毫秒数
PUBLISH channel message 发布一条消息到频道
PUNSUBSCRIBE [pattern [pattern …]] 停止发布到匹配给定模式的渠道的消息听
QUIT 关闭连接, 退出
RANDOMKEY 返回一个随机的key
READONLY Enables read queries for a connection to a cluster slave node
READWRITE Disables read queries for a connection to a cluster slave node
RENAME key newkey 将一个key重命名
RENAMENX key newkey 重命名一个key,新的key必须是不存在的key
REPLICAOF host port Make the server a replica of another instance, or promote it as master.
RESTORE key ttl serialized-value [REPLACE] Create a key using the provided serialized value, previously obtained using DUMP.
ROLE Return the role of the instance in the context of replication
RPOP key 从队列的右边出队一个元
RPOPLPUSH source destination 删除列表中的最后一个元素, 将其追加到另一个列表
RPUSH key value [value …] 从队列的右边入队一个元素
RPUSHX key value 从队列的右边入队一个元素, 仅队列存在时有效
SADD key member [member …] 添加一个或者多个元素到集合(set)里
SAVE 同步数据到磁盘上
SCARD key 获取集合里面的元素数量
SCRIPT DEBUG YES SYNC
SCRIPT EXISTS script [script …] Check existence of scripts in the script cache.
SCRIPT FLUSH 删除服务器缓存中所有Lua脚本.
SCRIPT KILL 杀死当前正在运行的 Lua 脚本.
SCRIPT LOAD script 从服务器缓存中装载一个Lua脚本.
SDIFF key [key …] 获得队列不存在的元素
SDIFFSTORE destination key [key …] 获得队列不存在的元素, 并存储在一个关键的结果集
SELECT index 选择新数据库
SET key value [EX seconds] [PX milliseconds] [NX XX]
SETBIT key offset value Sets or clears the bit at offset in the string value stored at key
SETEX key seconds value 设置key-value并设置过期时间 (单位: 秒)
SETNX key value 设置的一个关键的价值, 只有当该键不存在
SETRANGE key offset value Overwrite part of a string at key starting at the specified offset
SHUTDOWN [NOSAVE] [SAVE] 关闭服务
SINTER key [key …] 获得两个集合的交集
SINTERSTORE destination key [key …] 获得两个集合的交集, 并存储在一个关键的结果集
SISMEMBER key member 确定一个给定的值是一个集合的成员
SLAVEOF host port 指定当前服务器的主服务器
SLOWLOG subcommand [argument] 管理再分配的慢查询日志
SMEMBERS key 获取集合里面的所有元素
SMOVE source destination member 移动集合里面的一个元素到另一个集合
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern …]] [ASC DESC] [ALPHA] [STORE destination]
SPOP key [count] 删除并获取一个集合里面的元素
SRANDMEMBER key [count] 从集合里面随机获取一个元素
SREM key member [member …] 从集合里删除一个或多个元素
STRLEN key 获取指定key值的长度
SUBSCRIBE channel [channel …] 监听频道发布的消息
SUNION key [key …] 添加多个set元素
SUNIONSTORE destination key [key …] 合并set元素, 并将结果存入新的set里面
SWAPDB index index Swaps two Redis databases
SYNC 用于复制的内部命令
TIME 返回当前服务器时间
TOUCH key [key …] Alters the last access time of a key(s). Returns the number of existing keys specified.
TTL key 获取key的有效时间 (单位: 秒)
TYPE key 获取key的存储类型
UNLINK key [key …] Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.
UNSUBSCRIBE [channel [channel …]] 停止频道监听
UNWATCH 取消事务命令
WAIT numslaves timeout Wait for the synchronous replication of all the write commands sent in the context of the current connection
WATCH key [key …] 锁定key直到执行了 MULTI/EXEC 命令
XACK key group ID [ID …] Marks a pending message as correctly processed, effectively removing it from the pending entries list of the consumer group. Return value of the command is the number of messages successfully acknowledged, that is, the IDs we were actually able to resolve in the PEL.
XADD key ID field string [field string …] Appends a new entry to a stream
XCLAIM key group consumer min-idle-time ID [ID …] [IDLE ms] [TIME ms-unix-time] [RETRYCOUNT count] [FORCE] [JUSTID] Changes (or acquires) ownership of a message in a consumer group, as if the message was delivered to the specified consumer.
XDEL key ID [ID …] Removes the specified entries from the stream. Returns the number of items actually deleted, that may be different from the number of IDs passed in case certain IDs do not exist.
XGROUP [CREATE key groupname id-or-][SETIDkeyidor] [SETID key id-or-] [DESTROY key groupname] [DELCONSUMER key groupname consumername] Create, destroy, and manage consumer groups.
XINFO [CONSUMERS key groupname] [GROUPS key] [STREAM key] [HELP] Get information on streams and consumer groups
XLEN key Return the number of entires in a stream
XPENDING key group [start end count] [consumer] Return information and entries from a stream consumer group pending entries list, that are messages fetched but never acknowledged.
XRANGE key start end [COUNT count] Return a range of elements in a stream, with IDs matching the specified IDs interval
XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key …] ID [ID …] Return never seen elements in multiple streams, with IDs greater than the ones reported by the caller for each stream. Can block.
XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] STREAMS key [key …] ID [ID …] Return new entries from a stream using a consumer group, or access the history of the pending entries for a given consumer. Can block.
XREVRANGE key end start [COUNT count] Return a range of elements in a stream, with IDs matching the specified IDs interval, in reverse order (from greater to smaller IDs) compared to XRANGE
XTRIM key MAXLEN [~] count Trims the stream to (approximately if ‘~’ is passed) a certain size
ZADD key [NX XX] [CH] [INCR] score member [score member …]
ZCARD key 获取一个排序的集合中的成员数量
ZCOUNT key min max 返回分数范围内的成员数量
ZINCRBY key increment member 增量的一名成员在排序设置的评分
ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM MIN
ZLEXCOUNT key min max 返回成员之间的成员数量
ZPOPMAX key [count] Remove and return members with the highest scores in a sorted set
ZPOPMIN key [count] Remove and return members with the lowest scores in a sorted set
ZRANGE key start stop [WITHSCORES] 根据指定的index返回, 返回sorted set的成员列表
ZRANGEBYLEX key min max [LIMIT offset count] 返回指定成员区间内的成员, 按字典正序排列, 分数必须相同.
ZREVRANGEBYLEX key max min [LIMIT offset count] 返回指定成员区间内的成员, 按字典倒序排列, 分数必须相同
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] 返回有序集合中指定分数区间内的成员, 分数由低到高排序.
ZRANK key member 确定在排序集合成员的索引
ZREM key member [member …] 从排序的集合中删除一个或多个成员
ZREMRANGEBYLEX key min max 删除名称按字典由低到高排序成员之间所有成员.
ZREMRANGEBYRANK key start stop 在排序设置的所有成员在给定的索引中删除
ZREMRANGEBYSCORE key min max 删除一个排序的设置在给定的分数所有成员
ZREVRANGE key start stop [WITHSCORES] 在排序的设置返回的成员范围, 通过索引, 下令从分数高到低
ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count] 返回有序集合中指定分数区间内的成员, 分数由高到低排序.
ZREVRANK key member 确定指数在排序集的成员, 下令从分数高到低
ZSCORE key member 获取成员在排序设置相关的比分
ZUNIONSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM MIN
SCAN cursor [MATCH pattern] [COUNT count] 增量迭代key
SSCAN key cursor [MATCH pattern] [COUNT count] 迭代set里面的元素
HSCAN key cursor [MATCH pattern] [COUNT count] 迭代hash里面的元素
ZSCAN key cursor [MATCH pattern] [COUNT count] 迭代sorted sets里面的元素

1. 常见操作

1.1. 获取所有 key

keys 命令会会造成服务停顿, 不建议在生产上使用.
建议使用 scan 命令, 该命令在 redis 2.8 之后才有

1
2
3
4
5
6
# 统计个数
redis-cli --scan --pattern '*' | wc -l

# 批量删除
redis-cli --scan --pattern '*' | xargs -L 5000 redis-cli del
redis-cli EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 $pattern*

1.2. 批量导入

  1. 从文件中批量插入数据
  2. 大量数据插入

第二种比第一种多了一步数据格式的转化, 转化成了 AOF 命令的格式.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# cache.txt 中放的是批量操作, 如:
# SET count 1
# 将 cache.txt 转换成 AOF 格式
origin_redis_cmd_file=$1
delimiter="\r\n"

while read line; do
redis_cmd=($line)
# each command begins with *{number arguments in command}\r\n
printf "*${#redis_cmd[@]}${delimiter}"
# for each argument, we append ${length}\r\n{argument}\r\n
for cmd_part in $line; do
printf "\$${#cmd_part}${delimiter}${cmd_part}${delimiter}"
done
done < $origin_redis_cmd_file

# 使用管道批量导入
cat cache.txt | redis-cli --pipe