Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Redis (2) related commands

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

(1) brief introduction

The Redis command is used to perform operations on the redis service.

A redis client is required to execute commands on the redis service. The Redis client is in the redis installation package we downloaded earlier. The basic syntax of the Redis client is: redis-cli

[root@localhost ~] # / usr/local/redis-3.2.9/src/redis-cli 127.0.0.1 pingPONG127.0.0.1:6379 >

Remote login is:

[root@localhost] # / usr/local/redis-3.2.9/src/redis-cli-h 127.0.0.1-p 6379-a "redis123456" 127.0.0.1 pingPONG127.0.0.1:6379 >

(2) detailed explanation of the order

(1) Redis key (key). Redis key command keys used to manage redis

Syntax: 127.0.0.1 6379 > syntax

Examples are as follows:

127.0.0.1 set foo redisOK127.0.0.1:6379 > get foo "redis" 127.0.0.1 redis > del foo (integer) 1127.0.1 > get foo (nil)

In the above example, set is a command, foo is a key, get foo is to get the key, del foo is to delete the key, if deleted successfully, it will output (integer) 1, otherwise it will output (integer) 0

The following table shows the basic commands related to the redi key:

Numbered command describes 1DEL key this command deletes a specified key, if it exists. 2DUMP key this command returns the serialized version of the value stored in the specified key. 3EXISTS key this command checks to see if the key exists. The 4EXPIRE key seconds setting key expires / expires after the specified number of seconds. The 5EXPIREAT key timestamp setting expires / expires after the specified timestamp. The time here is in Unix timestamp format. 6PEXPIRE key milliseconds sets the expiration time of the key in milliseconds. 7PEXPIREAT key milliseconds-timestamp sets the expiration time of the key in milliseconds in the form of a Unix timestamp. 8KEYS pattern finds all keys that match the specified pattern. 9MOVE key db moves the key to another database. 10PERSIST key deletes the expiration time of the specified key and becomes immortal. 11PTTL key gets the remaining expiration time of the key. 12RANDOMKEY returns a random key from Redis. The name of the 13RENAME key newkey change key. 14PTTL key gets the remaining time, in milliseconds, that the key expires. 15RENAMENX key newkey rename the key if the new key does not exist. 16TYPE key returns the data type of the value stored in the key.

(2) redis string (string) Commands related to the redis string data type are used to manage redis string values. Syntax:

Redis 127.0.0.1 6379 > COMMAND KEY_NAME

Example:

127.0.1 china 6379 > set country chinaOK127.0.0.1:6379 > get country "china"

In the above example, set and get are the commands in redis, and country is the name of the key. The following table lists the basic commands for managing strings in redis:

Numbered command description 1SET key value this command sets the value of the specified key. 2GET key gets the value of the specified key. 3GETRANGE key start end gets the substring of the string stored on the key. 4GETSET key value sets the string value of the key and returns its old value. 5GETBIT key offset returns the bit value at the offset in the string value stored at the key. 6MGET key1 [key2..] Get the values of all given keys 7SETBIT key offset value set or clear the bit at the offset in the string value on the key 8SETEX key seconds value uses the key and expiration time to set the value 9SETNX key value sets the value of the key, only if the key does not exist, 10SETRANGE key offset value overrides part of the string at the key starting at the specified offset 11STRLEN key to get the length 12MSET key value of the value stored in the key [key value...] Set their values 13MSETNX key value [key value...] for multiple keys.] Set their values for multiple keys respectively. 14PSETEX key milliseconds value sets the key value and expiration time (in milliseconds) only when the key does not exist. 15INCR key increases the integer value of the key 116INCRBY key increment increases the integer value of the key by the given value 17INCRBYFLOAT key increment increases the floating-point value of the key by the given value 18DECR key increases the integer value of the key minus the integer value of the key 20APPEND key value appends the specified value to the key

(3) Redis Hash. Redis hash is a mapping table for field and value of type string, and hash is particularly suitable for storing objects. Each hash in Redis can store 232-1 key-value pairs (more than 4 billion).

127.0.0.1 arvin 6379 > HMSET myhash id "1" name "arvin" sex "man" address "china" OK127.0.0.1:6379 > hgetall myhash1) "id" 2) "1" 3) "name" 4) "arvin" 5) "sex" 6) "man" 7) "address" 8) "china" 127.0.0.1mm 6379 > hkeys myhash1) "id" 2) "name" 3) "sex" 4) "address" .0.0.1: 6379 > hvals myhash1) "1" 2) "arvin" 3) "man" 4) "china"

In the above example, some description information (id,name sex address) of redis is set to the hash table myhash.

The ordinal command instructs 1HDEL key field2 [field2] to delete one or more hash fields. 2HEXISTS key field determines whether a hash field exists. 3HGET key field gets the value stored in the hash field of the specified key. 4HGETALL key gets all fields and values stored in the hash of the specified key 5HINCRBY key field increment increases the integer value of the hash field by a given number 6HINCRBYFLOAT key field increment increases the floating-point value of the hash field by the given number 7HKEYS key gets all fields in the hash 8HLEN key gets the number of fields in the hash 9HMGET key field1 [field2] gets the value of all given hash fields 10HMSET key field1 value1 [field2 value2] for multiple hash fields Set their values 11HSET key field value set the string value 12HSETNX key field value of the hash field only if the field does not exist To set the value of the hash field 13HVALS key to get all the values in the hash

(4) the redis list is a simple list of strings sorted in the order in which they are inserted. You can add an element guide list at the head (left) or tail (right). A list can contain up to 4294967295 elements (more than 4 billion elements each).

127.0.0.1 LPUSH database mysql (integer) 1127.0.0.1 LPUSH database oracle (integer) 2127.0.0.1 > LPUSH database sql server (integer) 4127.0.0.1 > LPUSH database db2 (integer) 5127.0.0.1 > lrange database 041) "db2" 2) "server" 3) "sql" 4) "oracle" 5) "mysql"

The above child inserts four values into the redis list named database through LPUSH. Basic commands commonly used in the list:

The ordinal command instructs 1BLPOP key1 [key2] timeout to delete and get the first element in the list, or block until an element can be deleted with 2BRPOP key1 [key2] timeout and get the last element in the list, or block, until an element can be popped out of the list with 3BRPOPLPUSH source destination timeout, pushed to another list and returned to it Or block until an available 4LINDEX key index, through its index, gets the element from the list 5LINSERT key BEFORE/AFTER pivot value inserts the element before or after another element in the list, 6LLEN key gets the length of the list, 7LPOP key deletes and gets the first element in the list, 8LPUSH key value1 [value2], adds one or more values to the list 9LPUSHX key value only if the list exists Just add the value 10LRANGE key start stop to the list get a series of elements from the list 11LREM key count value delete the element from the list 12LSET key index value set the value of the element in the list 13LTRIM key start stop trim the specified range of the list 14RPOP key delete and get the last element in the list 15RPOPLPUSH source destination delete the last element in the list Attach it to another list and return 16RPUSH key value1 [value2] attach one or more values to the list 17RPUSHX key value appends values to the list only if the list exists

(5) Redis set set. The Set of Redis is an unordered collection of type string. Collection members are unique, which means that there can be no duplicate data in the collection. Collections in Redis are implemented through hash tables, so the complexity of adding, deleting and searching is O (1).

127.0.0.1 SADD myset "redis" (integer) 1127.0.0.1 integer > SADD myset "mysql" (integer) 1127.0.0.1 > SADD myset "mongodb" (integer) 1127.0.0.1 > SADD myset "mysql" (integer) 0127.0.0.1 > SMEMBERS MYSET (empty list or set) 127.0.0.1) SMEMBERS myset1) "mongodb" 2) "mysql" 3) "redis"

The above example inserts three values into the redis collection of myset through sadd.

The ordinal command states that 1SADD key member1 [member2] adds one or more members to the collection 2SCARD key gets the number of members in the collection 3SDIFF key1 [key2] minus multiple sets 4SDIFFSTORE destination key1 [key2] minus multiple sets and stores the result set in the key 5SINTER key1 [key2] intersects multiple sets 6SINTERSTORE destination key1 [key2] crosses multiple sets and stores the result set in the key 7SISMEMBER key member determines whether the given value is a member of the set 8SMOVE Source destination member moves members from one collection to another 9SPOP key removes and returns random members 10SRANDMEMBER key [count] get one or more random members from the collection 11SREM key member1 [member2] delete one or more members from the collection 12SUNION key1 [key2] add multiple sets 13SUNIONSTORE destination key1 [key2] add multiple sets and store the result set in the key 14SSCAN key cursor [MATCH pattern] [COUNT count] iterates over the elements in the collection incrementally

(6) Redis ordered sets (sorted set), like collections, are also collections of string character elements, and duplicate members are not allowed. The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large by scores. The members of an ordered set are unique, but the score can be repeated. The collection is implemented through a hash table, so the complexity of adding, deleting, and finding is all O (1). The maximum number of members in the collection is 4294967295 (each collection can store more than 4 billion members).

127.0.0.1 redis (integer) 1127.0.0.1 zadd mysorted 6379 > zadd mysorted 3 mongodb (integer) 1127.0.0.1 zadd mysorted 6379 > zadd mysorted 2 mysql (integer) 1127.0.1 mongodb 6379 > zadd mysorted 4 mysql (integer) 0127.0.0.1 mysql 6379 > zadd mysorted 6 mysql (integer) 0127.0.1) "mongodb" 3) "mysql" 127.0.1) "redis" 2) "mongodb" 3) Mysorted 0 10 withscores1) "redis" 2) "1" 3) "mongodb" 4) "3" 5) "mysql" 6) "6"

(7) Redis HyperLogLog is an algorithm used to do cardinality statistics, providing an approximation of the number of unique elements in the collection with a small amount of memory. HyperLogLog can accept multiple elements as input and give the cardinality estimate of the input element:

Cardinality: the number of different elements in the collection. For example, the cardinality of {'apple',' banana', 'cherry',' banana', 'apple'} is 3.

Estimates: the cardinality given by the algorithm is not accurate and may be slightly more or less than it actually is, but will be controlled within a reasonable range.

The advantage of HyperLogLog is that even if the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and small.

In Redis, each HyperLogLog key costs only 12 KB of memory to calculate the cardinality of nearly 2 ^ 64 different elements. This is in sharp contrast to collections that consume more memory with more elements when calculating the cardinality.

However, because HyperLogLog only calculates the cardinality based on the input element, it does not store the input element itself, so

HyperLogLog cannot return individual elements of input like a collection.

127.0.0.1 pfadd qaz "redis" (integer) 1127.0.0.1 integer 6379 > pfadd qaz "mysql" (integer) 1127.0.0.1 mysql > pfadd qaz "mongodb" (integer) 1127.0.0.1 integer 6379 > pfcount qaz (integer) 3 serial command description 1PFADD key element [element...] Adds the specified element to the specified HyperLogLog. 2PFCOUNT key [key...] Returns the cardinality estimate for the given HyperLogLog. 3PFMERGE destkey sourcekey [sourcekey...] Merge multiple HyperLogLog into a single HyperLogLog

(8) redis publish and subscribe.

Redis publish subscription (pub/sub) is a mode of message communication: the sender (pub) sends the message and the subscriber (sub) receives the message.

Redis publish subscription (pub/sub) implements a messaging system in which the sender (called the publisher in redis terminology) sends the message when the receiver (subscriber) receives the message. The link on which messages are transmitted is called a channel.

In Redis, clients can subscribe to any number of channels

First, enter subscribe redischat on one client and wait for input from another client, which is displayed as follows:

127.0.0.1 purl 6379 > subscribe redischat Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "redischat" 3) (integer) 11) "message" 2) "redischat" 3) "hello everyont" 1) "message" 2) "redischat" 3) "redis is very great caching technique"

Reopen a client and enter as follows:

127.0.0.1 publish redischat hello everyont (integer) 1127.0.0.1 publish redischat redis is very great caching technique (integer) 1127.0.0.1 redis is very great caching technique 6379 > publish redischat learn redis by lqb (integer) 1127.0.0.1 learn redis by lqb 6379 > publish redischat "learn redis by lqb" (integer) 1

The following table lists some basic commands related to Redis publish subscriptions.

The serial number command describes 1PSUBSCRIBE pattern [pattern...] Subscribe to one or more channels that match a given pattern. 2PUBSUB subcommand [argument [argument...]] View the status of the subscription and publishing system. 3PUBLISH channel message sends information to the specified channel. 4PUNSUBSCRIBE [pattern [pattern...]] Unsubscribe from all channels in a given mode. 5SUBSCRIBE channel [channel...] Subscribe to information for a given channel or channels. 6UNSUBSCRIBE [channel [channel...]] Unsubscribe from a given channel.

(9) Redis things. Redis transactions can execute more than one command at a time with two important guarantees:

All commands in the transaction are executed sequentially as a single isolated operation. In the course of execution, the transaction will not be interrupted by command requests sent by other clients.

Redis transactions are also atomic. Atoms mean either dealing with all commands or none at all.

A transaction goes through the following three stages from start to execution:

Start the business.

Order to join the team.

Execute the transaction.

Example: the Redis transaction is started by the command MULTI command, then you need to pass a list of commands that should be executed in the transaction, and then the entire transaction is executed by the EXEC command.

127.0.0.1 multiOK127.0.0.1:6379 > set foo "this is test page" QUEUED127.0.0.1:6379 > get book-nameQUEUED127.0.0.1:6379 > sadd tag "C++ is very good programming" QUEUED127.0.0.1:6379 > smembers tagQUEUED127.0.0.1:6379 > exec1) OK2) (nil) 3) (integer) 14) 1) "C++ is very good programming" 127.0.1 OK2 > multiOK127.0.0.1:6379 > set Mykey "redis" QUEUED127.0.0.1:6379 > get mykeyQUEUED127.0.0.1:6379 > incr visitorsQUEUED127.0.0.1:6379 > exec1) OK2) "redis" 3) (integer) 1

Basic commands related to redis:

The ordinal command indicates that 1DISCARD discards all commands issued after MULTI all commands issued after 2EXEC executes MULTI all commands issued after 3MULTI marks the beginning of the transaction block 4UNWATCH unmonitors all key. 5WATCH key [key...] Monitor the given key to determine the execution of the MULTI / EXEC block

(10) redis script. The Redis script uses the Lua interpreter to execute the script. Reids 2.6 supports the Lua environment through built-in support. The common command to execute a script is EVAL

127.0.1 KEYS 6379 > EVAL "return {KEYS [1], KEYS [2], ARGV [1], ARGV [2]}" 2 key1 key2 first second1) "key1" 2) "key2" 3) "first" 4) "second"

The following table lists some basic commands related to Redis scripts.

The serial number command describes 1EVAL script numkeys key [key...] Arg [arg...] Execute a Lua script. 2EVALSHA sha1 numkeys key [key...] Arg [arg...] Execute a Lua script. 3SCRIPT EXISTS script [script...] Check to see if scripts exist in the script cache. 4SCRIPT FLUSH removes all scripts from the script cache. 5SCRIPT KILL kills the currently executing script. 6SCRIPT LOAD script loads the specified Lua script into the script cache.

(11) Redis connection. The connection commands in Redis are basically used to manage client connections to the Redis server.

Redis 127.0.0.1 password 6379 > AUTH "password" OKredis 127.0.0.1 OKredis 6379 > PINGPONG

The following table lists some basic commands related to Redis connections.

The ordinal command states that 1AUTH password uses the given password authentication server 2ECHO message to print the given string information 3PING checks whether the server is running 4QUIT closes the current connection 5SELECT index changes the selected database of the current connection

(12) Redis server. Redis server commands are mainly used to manage redis services.

127.0.0.1 6379 > info# Serverredis_version:3.2.9redis_git_sha1:00000000redis_git_dirty:0redis_build_id:2f58f346024ca4bbredis_mode:standaloneos:Linux 3.10.0-327.el7.x86_64 x86_64arch_bits:64multiplexing_api:epollgcc_version:4.8.5process_id:2329run_id:bf5c0b97691ac975438fb6a954b13ed9a9d564batcp_port:6379uptime_in_seconds:97760uptime_in_days:1hz:10lru_clock:4162916executable:/usr/local/redis-3.2.9/ Src/redis-serverconfig_file:# Clientsconnected_clients:2client_longest_output_list:0client_biggest_input_buf:0blocked_clients:0# Memoryused_memory:913168used_memory_human:891.77Kused_memory_rss:2727936used_memory_rss_human:2.60Mused_memory_peak:913168used_memory_peak_human:891.77Ktotal_system_memory:3968024576total_system_memory_human:3.70Gused_memory_lua:40960used_memory_lua_human:40.00Kmaxmemory:0maxmemory_human:0Bmaxmemory_policy : noevictionmem_fragmentation_ratio:2.99mem_allocator:libc# Persistenceloading:0rdb_changes_since_last_save:0rdb_bgsave_in_progress:0rdb_last_save_time:1497328628rdb_last_bgsave_status:okrdb_last_bgsave_time_sec:0rdb_current_bgsave_time_sec:-1aof_enabled:0aof_rewrite_in_progress:0aof_rewrite_scheduled:0aof_last_rewrite_time_sec:-1aof_current_rewrite_time_sec:-1aof_last_bgrewrite_status: Okaof_last_write_status:ok# Statstotal_connections_received:6total_commands_processed:180instantaneous_ops_per_sec:0total_net_input_bytes:7123total_net_output_bytes:35960048instantaneous_input_kbps:0.00instantaneous_output_kbps:0.00rejected_connections:171sync_full:0sync_partial_ok:0sync_partial_err:0expired_keys:0evicted_keys:0keyspace_hits:70keyspace_misses:13pubsub_channels:1pubsub_patterns:0latest_fork_usec:113migrate_cached_sockets:0# Replicationrole:masterconnected_slaves:0master_repl_offset:0repl_backlog_active:0repl_backlog_size:1048576repl_backlog_first_byte_offset:0repl_backlog_histlen:0# CPUused_cpu_sys:33.59used_cpu_user:14.42used_cpu_sys_children:0.01used_cpu_user_children:0.00# Clustercluster_enabled:0# Keyspacedb0:keys=20 Expires=0,avg_ttl=0

The following table lists some basic commands related to the Redis server.

The serial number command states that 1BGREWRITEAOF asynchronously overwrites appended-only files 2BGSAVE saves the dataset asynchronously to disk 3CLIENT KILL [ip:port] [ID client-id] Kill or disconnect the connection of the specified client 4CLIENT LIST gets the list of client connections to the server 5CLIENT GETNAME gets the name of the current connection 6CLIENT PAUSE timeout stops processing commands from the client within a specified period of time 7CLIENT SETNAME connection-name sets the current connection name 8CLUSTER SLOTS Get cluster slot-to-node mapping array 9COMMAND get Redis command details array 10COMMAND COUNT get the total number of Redis commands 11COMMAND GETKEYS extract key give a complete Redis command 12BGSAVE save the dataset asynchronously to disk 13COMMAND INFO command-name [command-name...] An array 14CONFIG GET parameter that gets the details of a specific Redis command gets the value of the configuration parameter 15CONFIG REWRITE uses the in-memory configuration to rewrite the configuration file 16CONFIG SET parameter value sets the configuration parameter to a given value 17CONFIG RESETSTAT resets the statistics returned by INFO 18DBSIZE returns the number of keys in the selected database 19DEBUG OBJECT key gets debugging information about keys 20DEBUG SEGFAULT causes the server to crash 21FLUSHALL deletes all keys from all databases when the All keys in the former database 23INFO [section] get information and statistics about the server 24LASTSAVE gets the UNIX timestamp last successfully saved to disk 25MONITOR listener server receives all requests in real time 26ROLE returns the instance's role in the replication context 27SAVE saves the dataset synchronously to disk 28SHUTDOWN [NOSAVE] [SAVE] saves the dataset synchronously to disk Then turn off the server 29SLAVEOF host port to make the server a slave of another instance, or promote it as the primary server 30SLOWLOG subcommand [argument] manage Redis slow query logs 31SYNC the command for replication 32TIME returns the time of the current server

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report