1, Redis common commands
Redis is generally installed on linux, which is divided into server and client.
Start Redis server
Enter the following command on the terminal to start the Redis server:
$redis-server
Start Redis client
Enter the following command on the terminal to start Redis client:
#If the password is set, use the following format to start $redis-cli -h [ip] -p [port] -a [password] #Simple format $redis-cli
After entering, the following prompt will be returned:
redis 127.0.0.1:6379>
Note: 127.0.0.1 is the IP address of the local computer, and 6379 is the default port number for running Redis server.
Detailed explanation of common Redis commands
Redis commands can be roughly divided into the following types:
- server command
- client command
- Key command (key)
- Data type command
- Function application command
This manual of Redis common commands introduces the commands commonly used in Redis, including key commands and data type commands. The data type commands include String, List, Hash, Set and Sorted Set.
Key command
We know that Redis is a Key value database and uses Key to store value. Therefore, the Key command is a kind of command often used in Redis. Common Key commands are as follows:
command | explain |
---|---|
DEL | If the key exists, this command is used to delete the key |
DUMP | Used to serialize the given key and return the serialized value |
EXISTS | Used to check whether the key exists. If it exists, it returns 1; otherwise, it returns 0 |
EXPIRE | Set the expiration time of the key, in seconds |
EXPIREAT | Similar to EXPIRE, this command is used to set the expiration time for the key. The difference is that its time parameter value adopts the timestamp format. |
KEYS | This command is used to find the key matching the specified pattern |
MOVE | Move the key in the current database to the specified database (the default storage is 0 library, and any library from 1 to 15 is optional) |
PERSIST | This command is used to delete the expiration time of the key. Then the key will always exist and will not expire |
PEXPIRE | Set the expiration of key in milliseconds |
RANDOMKEY | Randomly return a key from the current database |
RENAME | Modify the name of the key |
SCAN | Cursor based iterators are used to iterate over all the keys that exist in the database. Cursor refers to the iterated cursor |
TTL | Used to check how long the key expires, in seconds |
TYPE | This command is used to get the data type of value. |
Hash command
Hash (hash hash) is one of the basic data types of Redis. It is stored in the form of string mapping table. Hash is especially suitable for storing objects. Common commands are as follows:
command | explain |
---|---|
HDEL | Used to delete one or more hash table fields |
HEXISTS | Used to determine whether a hash field exists |
HGET | Gets the value of the hash field stored in the key |
HGETALL | Gets all hash field values stored in the key |
HINCRBY | Perform integer increment operation for the specified field of the hash table stored in the key |
HKEYS | Gets all the fields of the hash table stored in the key |
HLEN | Gets the number of fields in the hash table stored in the key |
HSET | Used to set the value of the hash table field stored in the key |
HVALS | Used to get all the values in the hash table |
String command
Strings structure is one of the basic data types of Redis. We can operate it through related string commands, such as setting, retrieving, deleting, etc. String type has many application scenarios, such as the attention and cancellation of microblog fans.
The following describes the string commands of Changying in Redis:
command | explain |
---|---|
APPEND | This command appends value to the end of the value stored by key |
BITCOUNT | This command is used to calculate the number of bits set to 1 in the string. |
DECR | Subtract the integer value stored by the key by 1 |
DECRBY | Subtract the given decrement from the value stored in the key |
GET | Retrieves the value of the specified key |
GETBIT | For the string value stored by the key, obtain the bit on its specified offset |
GETRANGE | Returns the sub character of the string value in the key |
GETSET | Set the value of the given key to value and return the old value of the key |
INCR | Add 1 to the integer value stored by the key |
INCRBY | Add the value stored by the key to the given increment |
INCRBYFLOAT | Add the value stored in the key to the specified floating-point increment |
MGET | Get the value stored by one or more key s at one time |
MSET | This command allows multiple key value pairs to be set at the same time |
MSETNX | Used to set multiple key value pairs when none of the specified keys exist |
SET | Used to set the value of the specified key |
SETBIT | For the string value stored by key, set or clear the bit on the specified offset |
SETEX | Store the value value in the key and set the expiration time of the key to seconds (in seconds) |
STRLEN | Returns the length of the string value stored by the key |
SETNX | Set the value of the key when the key does not exist |
SETRANGE | Starting from offset, use the specified value to overwrite part of the string value stored by the key |
List command
List is one of the most commonly used data types in redis. Redis provides many commands for operating list types. Through these commands, you can add an element to the head or tail of the list.
The common commands for List are as follows:
command | explain |
---|---|
BLPOP | It is used to delete and return the first element in the list (header operation). If there is no element in the list, blocking will occur until the list timeout or pop-up elements are found |
BRPOP | It is used to delete and return the last element in the list (tail operation). If there is no element in the list, blocking will occur until the list timeout or pop-up elements are found |
BRPOPLPUSH | Take the last element from the list and insert it into the head of another list. If there are no elements in the list, blocking occurs until the wait times out or a pop-up element is found |
LINDEX | Get elements in the list by index |
LINSERT | Specifies that an element in the list inserts another element before or after it |
LLEN | Used to get the length of the list |
LPOP | Pop up the element from the head of the list. It defaults to the first element |
LPUSH | Insert one or more values at the head of the list |
LPUSHX | When the key of the stored list exists, it is used to insert the value into the list header |
LRANGE | Gets the elements within the specified range of the list |
LREM | Indicates that an element equal to value is deleted from the list. count indicates the number of deleted items, and 0 indicates all removed items |
LSET | Represents the value of an element in the list set by its index |
LTRIM | Keeps the element values within the specified range in the list |
Set command
Redis set data type consists of key value pairs, which are unordered and unique, which is similar to Python set. When the last element in the collection is removed, the data structure will be automatically deleted and the memory will also be reclaimed.
Because the set set can realize de duplication, it has many applicable scenarios, such as user lottery activities. Using the set set can ensure that the same user is not selected for the second time.
Common Redis set commands are as follows:
command | explain |
---|---|
SADD | Adds one or more elements to the collection and automatically removes duplicates |
SCARD | Returns the number of elements in the collection |
SDIFF | Find the difference set of two or more sets |
SDIFFSTORE | Find the difference set of two or more sets, and save the result to the specified set (key) |
SINTER | Find the intersection of two or more sets |
SINTERSTORE | Find the intersection of two or more sets and save the results to the specified set (key) |
SMEMBERS | View all elements in the collection |
SMOVE | Moves the elements in the collection to the specified collection |
SPOP | Pop up a specified number of elements |
SRANDMEMBER | Returns a specified number of elements randomly from the collection. By default, 1 element is returned |
SREM | Delete one or more elements. If the element does not exist, it will be ignored automatically |
SUNION | Find the union of two or more sets |
SUNIONSTORE | Find the union of two or more sets and save the results to the specified set (key) |
Zset command
zset is one of the most distinctive data types provided by Redis. Firstly, it is a set, which ensures the uniqueness of the internal value value. Secondly, it adds a score attribute to each value, and realizes ordering by sorting the scores. For example, the zset structure is used to store the student's score, the value represents the student's ID, and the score is the test score. We can sort the grades by score to get the students' ranking.
Common commands of zset are listed below, as follows:
command | explain |
---|---|
ZADD | Used to add one or more members to an ordered collection or update the score value of existing members |
ZCARD | Gets the number of members in an ordered collection |
ZCOUNT | Used to count the number of elements within the specified score value range in an ordered collection |
ZINCRBY | Used to increase the score of members in an ordered set |
ZINTERSTORE | Find the intersection of two or more ordered sets, and store the results in a new key |
ZRANGE | Returns the number of members in a specified index interval in an ordered collection |
ZRANGEBYLEX | Returns the number of members in a specified dictionary interval in an ordered set |
ZRANGEBYSCORE | Returns the members within the specified score range in an ordered set |
ZRANK | Returns the ranking of a specified member in an ordered collection |
ZREM | Remove one or more members from an ordered collection |
ZREMRANGEBYRANK | Remove all members within the specified ranking range in the ordered set |
ZREMRANGEBYSCORE | Removes all members within the specified score range from the ordered set |
ZREVRANGE | Returns the members in the specified interval in the ordered set. Through the index, the score is from high to low |
ZREVRANK | Returns the ranking of the specified members in the ordered set, and the members of the ordered set are sorted by decreasing points (from large to small) |
ZSCORE | Returns the score value of the specified member in the ordered set |
ZUNIONSTORE | Find the union of two or more ordered sets, and store the returned results in a new key |
2, C/C + + call interface to connect and operate Redis database
The above commands are Redis's own commands, but in our C/C + + code, we cannot directly execute these commands. We need to access Redis through the API provided by Redis.
Redis supports different programming languages, but calls different redis packages, for example: java corresponds to jedis; php corresponds to phpredis; C + + corresponds to hredis.
So we need to install hredis. After installing hredis, we can connect and operate Redis through the API provided by hredis.
The api provided by redis is provided in the header file < hiredis. H >. Let's take the contents of the file directly to understand some, and explain the usage of each function again.
hiredis.h
#ifndef __HIREDIS_H #define __HIREDIS_H #include "read.h" #include <stdarg.h> /* for va_list */ #include <sys/time.h> /* for struct timeval */ #include <stdint.h> /* uintXX_t, etc */ #include "sds.h" /* for sds */ #include "alloc.h" /* for allocation wrappers */ #define HIREDIS_MAJOR 0 #define HIREDIS_MINOR 14 #define HIREDIS_PATCH 0 #define HIREDIS_SONAME 0.14 /* Connection type can be blocking or non-blocking and is set in the * least significant bit of the flags field in redisContext. */ #define REDIS_BLOCK 0x1 /* Connection may be disconnected before being free'd. The second bit * in the flags field is set when the context is connected. */ #define REDIS_CONNECTED 0x2 /* The async API might try to disconnect cleanly and flush the output * buffer and read all subsequent replies before disconnecting. * This flag means no new commands can come in and the connection * should be terminated once all replies have been read. */ #define REDIS_DISCONNECTING 0x4 /* Flag specific to the async API which means that the context should be clean * up as soon as possible. */ #define REDIS_FREEING 0x8 /* Flag that is set when an async callback is executed. */ #define REDIS_IN_CALLBACK 0x10 /* Flag that is set when the async context has one or more subscriptions. */ #define REDIS_SUBSCRIBED 0x20 /* Flag that is set when monitor mode is active */ #define REDIS_MONITORING 0x40 /* Flag that is set when we should set SO_REUSEADDR before calling bind() */ #define REDIS_REUSEADDR 0x80 #define REDIS_KEEPALIVE_INTERVAL 15 /* seconds */ /* number of times we retry to connect in the case of EADDRNOTAVAIL and * SO_REUSEADDR is being used. */ #define REDIS_CONNECT_RETRIES 10 #ifdef __cplusplus extern "C" { #endif /* This is the reply object returned by redisCommand() */ typedef struct redisReply { int type; /* REDIS_REPLY_* */ long long integer; /* The integer when type is REDIS_REPLY_INTEGER */ size_t len; /* Length of string */ char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */ size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */ struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */ } redisReply; redisReader *redisReaderCreate(void); /* Function to free the reply objects hiredis returns by default. */ void freeReplyObject(void *reply); /* Functions to format a command according to the protocol. */ int redisvFormatCommand(char **target, const char *format, va_list ap); int redisFormatCommand(char **target, const char *format, ...); int redisFormatCommandArgv(char **target, int argc, const char **argv, const size_t *argvlen); int redisFormatSdsCommandArgv(sds *target, int argc, const char ** argv, const size_t *argvlen); void redisFreeCommand(char *cmd); void redisFreeSdsCommand(sds cmd); enum redisConnectionType { REDIS_CONN_TCP, REDIS_CONN_UNIX }; /* Context for a connection to Redis */ typedef struct redisContext { int err; /* Error flags, 0 when there is no error */ char errstr[128]; /* String representation of error when applicable */ int fd; int flags; char *obuf; /* Write buffer */ redisReader *reader; /* Protocol reader */ enum redisConnectionType connection_type; struct timeval *timeout; struct { char *host; char *source_addr; int port; } tcp; struct { char *path; } unix_sock; } redisContext; redisContext *redisConnect(const char *ip, int port); redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv); redisContext *redisConnectNonBlock(const char *ip, int port); redisContext *redisConnectBindNonBlock(const char *ip, int port, const char *source_addr); redisContext *redisConnectBindNonBlockWithReuse(const char *ip, int port, const char *source_addr); redisContext *redisConnectUnix(const char *path); redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv); redisContext *redisConnectUnixNonBlock(const char *path); redisContext *redisConnectFd(int fd); /** * Reconnect the given context using the saved information. * * This re-uses the exact same connect options as in the initial connection. * host, ip (or path), timeout and bind address are reused, * flags are used unmodified from the existing context. * * Returns REDIS_OK on successful connect or REDIS_ERR otherwise. */ int redisReconnect(redisContext *c); int redisSetTimeout(redisContext *c, const struct timeval tv); int redisEnableKeepAlive(redisContext *c); void redisFree(redisContext *c); int redisFreeKeepFd(redisContext *c); int redisBufferRead(redisContext *c); int redisBufferWrite(redisContext *c, int *done); /* In a blocking context, this function first checks if there are unconsumed * replies to return and returns one if so. Otherwise, it flushes the output * buffer to the socket and reads until it has a reply. In a non-blocking * context, it will return unconsumed replies until there are no more. */ int redisGetReply(redisContext *c, void **reply); int redisGetReplyFromReader(redisContext *c, void **reply); /* Write a formatted command to the output buffer. Use these functions in blocking mode * to get a pipeline of commands. */ int redisAppendFormattedCommand(redisContext *c, const char *cmd, size_t len); /* Write a command to the output buffer. Use these functions in blocking mode * to get a pipeline of commands. */ int redisvAppendCommand(redisContext *c, const char *format, va_list ap); int redisAppendCommand(redisContext *c, const char *format, ...); int redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); /* Issue a command to Redis. In a blocking context, it is identical to calling * redisAppendCommand, followed by redisGetReply. The function will return * NULL if there was an error in performing the request, otherwise it will * return the reply. In a non-blocking context, it is identical to calling * only redisAppendCommand and will always return NULL. */ void *redisvCommand(redisContext *c, const char *format, va_list ap); void *redisCommand(redisContext *c, const char *format, ...); void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen); #ifdef __cplusplus } #endif #endif
As can be seen from the file code, we need to know at least the following about using C/C + + to connect and operate Redis database:
- A structure: redisContext, which contains the information about our connection to Redis.
- Several functions:
- redisContext *redisConnect(const char *ip, int port); Connect Redis function
- void *redisCommand(redisContext *c, const char *format, …); Pass commands to Redis
- void redisFree(redisContext *c);
- void freeReplyObject(void *reply);
Function explanation
Function prototype: redisContext *redisConnect(const char *ip, int port)
Note: this function is used to connect to the redis database. The parameters are the ip address and port of the database. Generally, the port of the redis database is 6379
This function returns a structure redisContext.
Function prototype: void *redisCommand(redisContext *c, const char *format,...);
Note: this function executes commands, just like the SQL statements in the SQL database, except that it executes the operation commands in the redis database. The first parameter is the redisContext returned when connecting to the database, and the remaining parameters are variable parameters, just like the printf function of the C standard function. The return value is void *, which is generally cast into redisReply for further processing.
Function prototype void freeReplyObject(void *reply);
Note: release the memory occupied by the redisReply returned after the redisCommand is executed
Function prototype: void redisFree(redisContext *c);
Description: release the connection generated by redisConnect().
Synchronization API
Connect to redis database
The redisConnect function is used to create a redisContext. This context is the connection status held by hiredis. The redisConnect structure has an integer err variable to identify the connection error code. If there is a connection error, it is a non-zero value. The variable errstr identifies the text description of the connection result. More information on this will be described in the Errors section below. When you use redisConnect to create a connection, you should check the err variable to determine whether the connection is established normally.
redisContext *c = redisConnect("127.0.0.1", 6379); if (c != NULL && c->err) {undefined printf("Error: %s\n", c->errstr); // handle error }
Send command to redis
There are many ways to send commands to redis.
redisCommand is introduced first. This function is similar to the use of printf, such as
reply = redisCommand(context, "SET foo bar");
Similar to the s% format of printf, such as
reply = redisCommand(context, "SET foo %s", value);
When you need to send binary safe commands, you can use the format of% b, and you need a string pointer and size_ The string length parameter of type T is as follows
reply = redisCommand(context, "SET foo %b", value, (size_t) valuelen);
Within the API, Hiredis splits commands according to different parameters into standard commands for operating the redis database. You can format multiple parameters to construct redis commands, as shown below
reply = redisCommand(context, "SET key:%s %s", myid, value);
Process redis response
When the command is successfully executed, redisCommand will have the corresponding return value. If an error occurs, the return value is NULL and the err variable in the redisReply structure will be set to the corresponding value (refer to the Errors chapter). Once an error occurs, the context cannot be reused and you need to establish a new connection.
After redisCommand is executed, the return value type is redisReply. The execution of the command can be determined by the type variable in the redisReply structure.
- REDIS_REPLY_STATUS:
- Returns a command whose execution result is status. For example, the return value of the set command is REDIS_REPLY_STATUS, and then only when the returned information is "OK", it indicates that the command is executed successfully. The text information can be obtained through reply - > STR, and the information length can be obtained through reply - > len.
- REDIS_REPLY_ERROR:
- Error returned. The error message can get the text message through reply - > STR and the message length through reply - > len.
- REDIS_REPLY_INTEGER:
- Returns an integer identifier. You can get a value of type long long through the reply - > integer variable.
- REDIS_REPLY_NIL:
- Return the nil object, indicating that there is no data to access.
- REDIS_REPLY_STRING:
- Returns a string identifier. You can get the specific value through reply - > STR and the information length through reply - > len.
- REDIS_REPLY_ARRAY:
- Returns the dataset ID. The number of elements in the dataset can be obtained through reply - > elements. Each element is a redisReply object, and the element value can be obtained in the form of reply - > element [... index...]. * for the operation of obtaining multiple data results.
After the command call is executed, redisReply should be released through freeReplyObject(). Note that nested objects (such as arrays) do not need to be nested for release, which is harmful and will cause memory damage.
Important: the current version of hiredis (0.10.0) releases the reports object itself when using the asynchronous API. This means that you do not need to actively call freeReplyObject when using asynchronous APIs. The relpy object will be automatically released when the callback returns. However, this behavior may change in future versions, so please pay close attention to the upgrade log when upgrading.
Clean up connection resources
Disconnect and release context using the following function
void redisFree(redisContext *c);
This function immediately closes the socket and releases the resources allocated when creating the context.
Send multiple command parameters
Similar to the redisCommand function, the redisCommandArgv function can be used to transfer multiple command parameters. The function prototype is
void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);
Commands like lpush, del key1 key2..., zadd key score1 member1 score2 member2... Where argc is the number of passed parameters, argv is mainly used for the value of passed strings, and argvlen is the size of each string.
Access Redis code instance
#ifdef _cplusplus extern "C" { #endif #include <stdio.h> #include <hiredis/hiredis.h> void main() { redisContext * conn = redisConnect("127.0.0.1", 6379); if (conn->err) { printf("connection error\n"); redisFree(conn); return; } redisReply * reply = redisCommand(conn, "set foo 1234"); freeReplyObject(reply); reply = redisCommand(conn, "get foo"); printf("%s\n", reply->str); freeReplyObject(reply); redisFree(conn); } #ifdef _cplusplus } #endif