Lesson 24-C++ Operating Redis Database

Redis is an open-source key-value storage system widely used in caching, message queues, and various other application scenarios. In C++, operating a Redis database typically involves using third-party libraries such as hiredis or cpp_redis. Below, we will detail how to use these libraries to operate a Redis database.

Installing Third-Party Libraries

First, you need to install the corresponding C++ Redis client library. Here, we use hiredis as an example:

hiredis

# Debian/Ubuntu
sudo apt-get install libhiredis-dev

# CentOS/RHEL
sudo yum install hiredis-devel

Basic Usage

Connecting to the Redis server

#include <hiredis/hiredis.h>

int main() {
    redisContext *c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
        if (c) {
            std::cerr << "Error: " << c->errstr << std::endl;
            redisFree(c);
        } else {
            std::cerr << "Connection error" << std::endl;
        }
        return 1;
    }
    // Use Redis
    redisFree(c);
    return 0;
}

Sending commands

redisReply *reply = (redisReply *)redisCommand(c, "SET key value");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Getting replies

redisReply *reply = (redisReply *)redisCommand(c, "GET key");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
if (reply->type == REDIS_REPLY_STRING) {
    std::cout << "Value: " << reply->str << std::endl;
}
freeReplyObject(reply);

Asynchronous Operations

Redis also supports asynchronous operations, which are very useful for high-concurrency applications.

Creating an asynchronous context

redisContext *ac = redisAsyncConnect("127.0.0.1", 6379);
if (ac->err) {
    std::cerr << "Error: " << ac->errstr << std::endl;
    return 1;
}

Registering callback functions

redisLibeventAttach(ac, NULL);
redisAsyncCommand(ac, asyncCommandCallback, NULL, "SET key value");

Handling events

struct event_base *base = event_base_new();
while (true) {
    event_base_dispatch(base);
}
event_base_free(base);

Key-Value Operations

Setting a key-value pair

redisReply *reply = (redisReply *)redisCommand(c, "SET mykey myvalue");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Getting a key’s value

redisReply *reply = (redisReply *)redisCommand(c, "GET mykey");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
if (reply->type == REDIS_REPLY_STRING) {
    std::cout << "Value: " << reply->str << std::endl;
}
freeReplyObject(reply);

Deleting a key

redisReply *reply = (redisReply *)redisCommand(c, "DEL mykey");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Advanced Data Types

Redis supports multiple data types, including strings (Strings), lists (Lists), sets (Sets), sorted sets (Sorted Sets), and hashes (Hashes).

List operations

redisReply *reply = (redisReply *)redisCommand(c, "LPUSH mylist item1 item2");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Set operations

redisReply *reply = (redisReply *)redisCommand(c, "SADD myset item1");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Sorted set operations

redisReply *reply = (redisReply *)redisCommand(c, "ZADD myzset 1.0 item1");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Hash operations

redisReply *reply = (redisReply *)redisCommand(c, "HSET myhash field1 value1");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

Transactions

Redis supports a simple transaction mechanism that allows users to bundle multiple commands into a single transaction.

redisReply *reply = (redisReply *)redisCommand(c, "MULTI");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

redisReply *reply2 = (redisReply *)redisCommand(c, "SET key1 value1");
if (reply2 == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply2);

redisReply *reply3 = (redisReply *)redisCommand(c, "EXEC");
if (reply3 == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply3);

Publish/Subscribe

Redis supports the publish/subscribe pattern, which can be used to implement message queue functionality.

Creating a subscription context

redisContext *sc = redisSubscribeContext();
if (sc == NULL) {
    std::cerr << "Error creating subscribe context" << std::endl;
    return 1;
}

Subscribing to a channel

redisLibeventAttach(sc, NULL);
redisAppendCommand(sc, "SUBSCRIBE channel1");

Handling events

struct event_base *base = event_base_new();
while (true) {
    event_base_dispatch(base);
}
event_base_free(base);

Error Handling

For any Redis operation, you need to check the return value to determine whether the operation was successful.

if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}

Performance Optimization

Batch operations

Use pipelining to reduce network round trips.

redisReply *reply = (redisReply *)redisCommand(c, "MULTI");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);

redisReply *reply2 = (redisReply *)redisCommand(c, "SET key1 value1");
if (reply2 == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply2);

redisReply *reply3 = (redisReply *)redisCommand(c, "EXEC");
if (reply3 == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply3);

Connection pool

Use a connection pool to reuse connections and reduce connection establishment time.

class RedisConnectionPool {
public:
    std::shared_ptr<redisContext> getConnection() {
        if (!m_freeConnections.empty()) {
            std::shared_ptr<redisContext> conn = m_freeConnections.front();
            m_freeConnections.pop();
            return conn;
        }
        return nullptr;
    }

    void releaseConnection(std::shared_ptr<redisContext> conn) {
        m_freeConnections.push(conn);
    }

private:
    std::queue<std::shared_ptr<redisContext>> m_freeConnections;
};

Security

Authentication

Redis supports password authentication.

redisContext *c = redisConnectAuth("127.0.0.1", 6379, "yourpassword");
if (c == NULL || c->err) {
    if (c) {
        std::cerr << "Error: " << c->errstr << std::endl;
        redisFree(c);
    } else {
        std::cerr << "Connection error" << std::endl;
    }
    return 1;
}

SSL/TLS encryption

For scenarios with high security requirements, SSL/TLS can be used for encrypted communication.

redisContext *c = redisConnect_TLS("127.0.0.1", 6379, NULL, 0, NULL, NULL, 0);
if (c == NULL || c->err) {
    if (c) {
        std::cerr << "Error: " << c->errstr << std::endl;
        redisFree(c);
    } else {
        std::cerr << "Connection error" << std::endl;
    }
    return 1;
}

Logging and Monitoring

To ensure the stable operation of the Redis service, it is necessary to log Redis operations and monitor performance.

Logging

You can use Redis’s logging feature to record operation logs and analyze them regularly to identify potential issues.

Performance monitoring

Use Redis built-in commands such as INFO to obtain server status information, or use third-party tools like redis-cli, redis-benchmark, etc., for performance testing.

// Get Redis server information
redisReply *reply = (redisReply *)redisCommand(c, "INFO");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
std::cout << "Server Info: " << reply->str << std::endl;
freeReplyObject(reply);

Fault Recovery

Automatic reconnection

Implement an automatic reconnection mechanism on the client side to handle network fluctuations or server restarts.

bool reconnect() {
    if (c != NULL) {
        redisFree(c);
    }
    c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
        std::cerr << "Error: " << c->errstr << std::endl;
        return false;
    }
    return true;
}

void handle_command() {
    while (true) {
        redisReply *reply = (redisReply *)redisCommand(c, "GET key");
        if (reply == NULL) {
            std::cerr << "Error: " << c->errstr << std::endl;
            if (!reconnect()) {
                std::cerr << "Failed to reconnect" << std::endl;
                break;
            }
            continue;
        }
        freeReplyObject(reply);
        break;
    }
}

Data backup and recovery

Regularly back up Redis data and restore it when necessary.

// Perform RDB snapshot backup
redisReply *reply = (redisReply *)redisCommand(c, "BGSAVE");
if (reply == NULL) {
    std::cerr << "Error: " << c->errstr << std::endl;
    return 1;
}
freeReplyObject(reply);
Share your love