Working with Redis Lists

Introduction to Redis Lists

Welcome back! In the previous lessons, we explored how to connect to Redis and perform operations with numbers. Now, let's explore another essential Redis data structure: lists. Lists in Redis are a great way to store ordered collections of items, such as names, messages, or tasks.

What You'll Learn

By the end of this lesson, you'll know how to:

  1. Use the RPUSH command to add items to a Redis list from C++.
  2. Retrieve list items using the LRANGE command in C++.
  3. Understand how to access specific elements in a list using the LINDEX command.

Example: Working with Redis Lists in C++

Here's a quick look at how you'll be working with lists in Redis using C++ and Boost.Redis:

C++
#include <boost/redis.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/consign.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <optional>

#include <boost/redis/src.hpp> 

namespace net = boost::asio;
using boost::redis::connection;
using boost::redis::config;
using boost::redis::logger;
using boost::redis::request;
using boost::redis::response;

int main() {
    try {
        net::io_context ioc;

        auto conn = std::make_shared<connection>(ioc.get_executor());

        config cfg; // defaults to 127.0.0.1:6379
        conn->async_run(cfg, logger{logger::level::disabled},
                        net::consign(net::detached, conn));

        // Build the pipeline
        request req;
        req.push("RPUSH", "students", "Alice", "Bob", "Charlie");
        req.push("LRANGE", "students", "0", "-1");
        req.push("LINDEX", "students", "1");

        // NOTE: response<Ts...> stores boost::system::result<T, adapter::error> for each T
        response<std::int64_t, std::vector<std::string>, std::optional<std::string>> resp;

        conn->async_exec(req, resp,
            [conn, &resp](boost::system::error_code ec, std::size_t) {
                if (ec) {
                    std::cerr << "Error executing Redis commands: " << ec.message() << "\n";
                    conn->cancel();
                    return;
                }

                // RPUSH
                const auto& rpush_res = std::get<0>(resp); // result<long, error>
                if (rpush_res) {
                    std::cout << "RPUSH Response (list length): " << rpush_res.value() << "\n";
                } else {
                    std::cout << "RPUSH failed\n";
                }

                // LRANGE
                const auto& lrange_res = std::get<1>(resp); // result<vector<string>, error>
                if (lrange_res) {
                    const auto& students = lrange_res.value();
                    std::cout << "Students in the list: ";
                    for (const auto& name : students) std::cout << name << ' ';
                    std::cout << "\n";
                } else {
                    std::cout << "LRANGE failed\n";
                }

                // LINDEX
                const auto& lindex_res = std::get<2>(resp); // result<optional<string>, error>
                if (lindex_res) {
                    const auto& student_opt = lindex_res.value();
                    if (student_opt) {
                        std::cout << "Student at index 1: " << *student_opt << "\n";
                    } else {
                        std::cout << "Student at index 1: (nil)\n";
                    }
                } else {
                    std::cout << "LINDEX failed\n";
                }

                conn->cancel(); // stop background ops
            });

        ioc.run();
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
        return 1;
    }
    return 0;
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal