redis Quick Start Manual

Article catalog

I came to the application of redis module in the past two days. I turned around and suddenly found that I had written so many articles on the principle of redis, but I actually stumbled on the basis of basic use. (cluster? Simple. Master-slave? easy. Interpolation? emmm, let me think twice,,,) Originally, I wanted to write this article tomorrow, but I think tomorrow is another day of running around. I have to take time to promote the development progress. I'd better add a class tonight.

It's all listed here. It saves you looking for others everywhere.

Environment configuration

The environment configuration has been written before, so just link directly. Redis environment setup and configuration hiredis is a one-stop service from installation to operation

No problem.

I won't say more nonsense. Here's a very important point: If you have a heavy ideological burden on SQL, you must empty your brain first. It is not difficult to change from SQL to NoSQL, but it is not just a "I want to change". You can use JSON in the early stage, which is what I did.

Chinese garbled code problem solving

If it is operated directly by the client: ./redis-cli --raw

If code operation is used (I think code should be used for batch operation): JSON.dump()

Remote connection trust problem

When reporting an error, several solutions will be provided, which is quite humanized.

Basic operation of redis key

Basic syntax: redis 127.0.0.1:6379 > command key_ NAME

command

describe

DEL key

This command is used to delete a key when it exists.

DUMP key

Serialize the given key and return the serialized value.

EXISTS key

Check whether the given key exists.

EXPIRE key seconds

Sets the expiration time in seconds for the given key.

EXPIREAT key timestamp

The function of EXPIREAT is similar to that of EXPIRE. Both of them are used to set the expiration time for the key. The difference is that the time parameter accepted by the express command is UNIX timestamp.

PEXPIRE key milliseconds

Set the expiration time of the key in milliseconds.

PEXPIREAT key milliseconds-timestamp

Set the time stamp (unix timestamp) of the key expiration time in milliseconds

KEYS pattern

Find all key s that match the given pattern.

MOVE key db

Move the key of the current database to the given database db.

PERSIST key

Remove the expiration time of the key, and the key will be persistent.

PTTL key

Returns the remaining expiration time of the key in milliseconds.

TTL key

Returns the TTL (time to live) of a given key in seconds.

RANDOMKEY

Randomly return a key from the current database.

RENAME key newkey

Modify the name of the key

RENAMENX key newkey

Change the name of the key to newkey only if the newkey does not exist.

SCAN cursor [MATCH pattern] [COUNT count]

Iterates over the database keys in the database.

TYPE key

Returns the type of the value stored by the key.

String command

command

describe

SET key value

Set the value of the specified key

GET key

Gets the value of the specified key.

GETRANGE key start end

Returns the sub character of the string value in the key

GETSET key value

Set the value of the given key to value and return the old value of the key.

GETBIT key offset

For the string value stored by key, obtain the bit on the specified offset.

MGET key1 [key2...]

Gets the values of all (one or more) given key s.

SETBIT key offset value

Set or clear the bit on the specified offset for the string value stored by key.

SETEX key seconds value

Associate the value value with the key and set the expiration time of the key to seconds (in seconds).

SETNX key value

The key value can only be set when the key does not exist.

SETRANGE key offset value

Overwrite the string value stored by the given key with the value parameter, starting from the offset.

STRLEN key

Returns the length of the string value stored by the key.

MSET key value [key value ...]

Set one or more key value pairs at the same time.

MSETNX key value [key value ...]

Set one or more key value pairs at the same time if and only if all given keys do not exist.

PSETEX key milliseconds value

This command is similar to the SETEX command, but it sets the lifetime of the key in milliseconds instead of seconds, as in the SETEX command.

INCR key

Increment the numeric value stored in the key by one.

INCRBY key increment

Add the value stored by the key to the given increment value.

INCRBYFLOAT key increment

Add the value stored by the key to the given floating-point increment value.

DECR key

Subtract the numeric value stored in the key by one.

DECRBY key decrement

key subtracts the given decrement from the stored value.

APPEND key value

If the key already exists and is a string, the APPEND command appends the specified value to the end of the original value of the key.

Hash command

command

describe

HDEL key field1 [field2]

Delete one or more hash table fields

HEXISTS key field

Check whether the specified field exists in the hash table key.

HGET key field

Gets the value of the specified field stored in the hash table.

HGETALL key

Gets all fields and values of the specified key in the hash table

HINCRBY key field increment

Add increment to the integer value of the specified field in the hash table key.

HINCRBYFLOAT key field increment

Adds increment to the floating-point value of the specified field in the hash table key.

HKEYS key

Gets the fields in all hash tables

HLEN key

Gets the number of fields in the hash table

HMGET key field1 [field2]

Gets the value of all the given fields

HMSET key field1 value1 [field2 value2 ]

Set multiple field value pairs to the hash table key at the same time.

HSET key field value

Set the value of the field field in the hash table key to value.

HSETNX key field value

Set the value of the hash table field only if the field field does not exist.

HVALS key

Gets all values in the hash table.

HSCAN key cursor [MATCH pattern] [COUNT count]

Iterates over key value pairs in the hash table.

list

command

describe

BLPOP key1 [key2 ] timeout

Move out and get the first element of the list. If there is no element in the list, the list will be blocked until the waiting timeout or pop-up element is found.

BRPOP key1 [key2 ] timeout

Move out and get the last element of the list. If there are no elements in the list, the list will be blocked until the waiting timeout or pop-up elements are found.

BRPOPLPUSH source destination timeout

Pop up a value from the list, insert the pop-up element into another list and return it; If the list has no elements, the list is blocked until the wait times out or a pop-up element is found.

LINDEX key index

Get elements in the list by index

LINSERT key BEFORE

AFTER pivot value

LLEN key

Get list length

LPOP key

Move out and get the first element of the list

LPUSH key value1 [value2]

Inserts one or more values into the list header

LPUSHX key value

Inserts a value into an existing list header

LRANGE key start stop

Gets the elements within the specified range of the list

LREM key count value

Remove list elements

LSET key index value

Sets the value of a list element by index

LTRIM key start stop

Trim a list, that is, make the list keep only the elements within the specified interval, and the elements not within the specified interval will be deleted.

RPOP key

Remove the last element of the list, and the return value is the removed element.

RPOPLPUSH source destination

Removes the last element of the list, adds it to another list, and returns

RPUSH key value1 [value2]

Add one or more values to the list

RPUSHX key value

Add a value to an existing list

aggregate

command

describe

SADD key member1 [member2]

Add one or more members to the collection

SCARD key

Gets the number of members of the collection

SDIFF key1 [key2]

Returns the difference between the first set and other sets.

SDIFFSTORE destination key1 [key2]

Returns the difference set of all given sets and stores it in destination

SINTER key1 [key2]

Returns the intersection of all given sets

SINTERSTORE destination key1 [key2]

Returns the intersection of all given sets and stores them in destination

SISMEMBER key member

Judge whether the member element is a member of the set key

SMEMBERS key

Returns all members in the collection

SMOVE source destination member

Move the member element from the source collection to the destination collection

SPOP key

Removes and returns a random element in the collection

SRANDMEMBER key [count]

Returns one or more random numbers in a collection

SREM key member1 [member2]

Remove one or more members from the collection

SUNION key1 [key2]

Returns the union of all given sets

SUNIONSTORE destination key1 [key2]

The union of all given sets is stored in the destination set

SSCAN key cursor [MATCH pattern] [COUNT count]

Iterating over elements in a collection

Connection command

command

describe

ECHO message

Print string

PING

Check whether the service is running

QUIT

Close current connection

SELECT index

Switch to the specified database

Use case

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
#include <win32.h>

int main(int argc, char **argv) {
    unsigned int j, isunix = 0;
    redisContext *c;
    redisReply *reply;
    const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";

    if (argc > 2) {
        if (*argv[2] == 'u' || *argv[2] == 'U') {
            isunix = 1;
            /* in this case, host is the path to the unix socket */
            printf("Will connect to unix socket @%s\n", hostname);
        }
    }

    int port = (argc > 2) ? atoi(argv[2]) : 6379;

    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    if (isunix) {
        c = redisConnectUnixWithTimeout(hostname, timeout);
    } else {
        c = redisConnectWithTimeout(hostname, port, timeout);
    }
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        exit(1);
    }

    /* PING server */
    reply = redisCommand(c,"PING");
    printf("PING: %s\n", reply->str);
    freeReplyObject(reply);

    /* Set a key */
    reply = redisCommand(c,"SET %s %s", "foo", "hello world");
    printf("SET: %s\n", reply->str);
    freeReplyObject(reply);

    /* Set a key using binary safe API */
    reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
    printf("SET (binary API): %s\n", reply->str);
    freeReplyObject(reply);

    /* Try a GET and two INCR */
    reply = redisCommand(c,"GET foo");
    printf("GET foo: %s\n", reply->str);
    freeReplyObject(reply);

    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);
    /* again ... */
    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);

    /* Create a list of numbers, from 0 to 9 */
    reply = redisCommand(c,"DEL mylist");
    freeReplyObject(reply);
    for (j = 0; j < 10; j++) {
        char buf[64];

        snprintf(buf,64,"%u",j);
        reply = redisCommand(c,"LPUSH mylist element-%s", buf);
        freeReplyObject(reply);
    }

    /* Let's check what we have inside the list */
    reply = redisCommand(c,"LRANGE mylist 0 -1");
    if (reply->type == REDIS_REPLY_ARRAY) {
        for (j = 0; j < reply->elements; j++) {
            printf("%u) %s\n", j, reply->element[j]->str);
        }
    }
    freeReplyObject(reply);

    /* Disconnects and frees the context */
    redisFree(c);

    return 0;
}

About redisCommand and redisReply

At present, there is not much information on hand. Take these out first:

void* redisCommand(redisContext c,const char format,...); 

The return value is a pointer of void type, which is actually a pointer of redisReply type

The redisReply structure is defined as follows:

/* 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;

The following are some common redis errors and return value types:

#define REDIS_ERR -1
#define REDIS_OK 0
#define REDIS_ERR_IO 1 /* Error in read or write */
#define REDIS_ERR_EOF 3 /* End of file */
#define REDIS_ERR_PROTOCOL 4 /* Protocol error */
#define REDIS_ERR_OOM 5 /* Out of memory */
#define REDIS_ERR_OTHER 2 /* Everything else... */     
#define REDIS_REPLY_STRING 1 / / returns a string. View the STR and Len fields
#define REDIS_REPLY_ARRAY 2 / / returns an array. View the value of elements (the number of arrays). Access the array elements through element[index]. Each array element is a pointer to a redisReply object
#define REDIS_REPLY_INTEGER 3 / / returns an integer. Get the value from the integer field
#define REDIS_REPLY_NIL 4 / / no data is returned
#define REDIS_REPLY_STATUS 5 / / indicates the status. The content is viewed through the str field. The string length is the len field
#define REDIS_REPLY_ERROR 6 / / indicates an error. View the error information, as shown in the str field above

Added by mo0ness on Mon, 29 Nov 2021 10:08:22 +0200