| CARVIEW |
Select Language
HTTP/2 200
date: Tue, 30 Dec 2025 00:15:23 GMT
content-type: text/html; charset=utf-8
vary: X-PJAX, X-PJAX-Container, Turbo-Visit, Turbo-Frame, X-Requested-With,Accept-Encoding, Accept, X-Requested-With
etag: W/"92406f13c0962d9f5769911f8b0dfc4f"
cache-control: max-age=0, private, must-revalidate
strict-transport-security: max-age=31536000; includeSubdomains; preload
x-frame-options: deny
x-content-type-options: nosniff
x-xss-protection: 0
referrer-policy: no-referrer-when-downgrade
content-security-policy: default-src 'none'; base-uri 'self'; child-src github.githubassets.com github.com/assets-cdn/worker/ github.com/assets/ gist.github.com/assets-cdn/worker/; connect-src 'self' uploads.github.com www.githubstatus.com collector.github.com raw.githubusercontent.com api.github.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com *.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com github.githubassets.com objects-origin.githubusercontent.com copilot-proxy.githubusercontent.com proxy.individual.githubcopilot.com proxy.business.githubcopilot.com proxy.enterprise.githubcopilot.com *.actions.githubusercontent.com wss://*.actions.githubusercontent.com productionresultssa0.blob.core.windows.net/ productionresultssa1.blob.core.windows.net/ productionresultssa2.blob.core.windows.net/ productionresultssa3.blob.core.windows.net/ productionresultssa4.blob.core.windows.net/ productionresultssa5.blob.core.windows.net/ productionresultssa6.blob.core.windows.net/ productionresultssa7.blob.core.windows.net/ productionresultssa8.blob.core.windows.net/ productionresultssa9.blob.core.windows.net/ productionresultssa10.blob.core.windows.net/ productionresultssa11.blob.core.windows.net/ productionresultssa12.blob.core.windows.net/ productionresultssa13.blob.core.windows.net/ productionresultssa14.blob.core.windows.net/ productionresultssa15.blob.core.windows.net/ productionresultssa16.blob.core.windows.net/ productionresultssa17.blob.core.windows.net/ productionresultssa18.blob.core.windows.net/ productionresultssa19.blob.core.windows.net/ github-production-repository-image-32fea6.s3.amazonaws.com github-production-release-asset-2e65be.s3.amazonaws.com insights.github.com wss://alive.github.com wss://alive-staging.github.com api.githubcopilot.com api.individual.githubcopilot.com api.business.githubcopilot.com api.enterprise.githubcopilot.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com copilot-workspace.githubnext.com objects-origin.githubusercontent.com; frame-ancestors 'none'; frame-src viewscreen.githubusercontent.com notebooks.githubusercontent.com; img-src 'self' data: blob: github.githubassets.com media.githubusercontent.com camo.githubusercontent.com identicons.github.com avatars.githubusercontent.com private-avatars.githubusercontent.com github-cloud.s3.amazonaws.com objects.githubusercontent.com release-assets.githubusercontent.com secured-user-images.githubusercontent.com/ user-images.githubusercontent.com/ private-user-images.githubusercontent.com opengraph.githubassets.com marketplace-screenshots.githubusercontent.com/ copilotprodattachments.blob.core.windows.net/github-production-copilot-attachments/ github-production-user-asset-6210df.s3.amazonaws.com customer-stories-feed.github.com spotlights-feed.github.com objects-origin.githubusercontent.com *.githubusercontent.com; manifest-src 'self'; media-src github.com user-images.githubusercontent.com/ secured-user-images.githubusercontent.com/ private-user-images.githubusercontent.com github-production-user-asset-6210df.s3.amazonaws.com gist.github.com github.githubassets.com; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com; upgrade-insecure-requests; worker-src github.githubassets.com github.com/assets-cdn/worker/ github.com/assets/ gist.github.com/assets-cdn/worker/
server: github.com
content-encoding: gzip
accept-ranges: bytes
set-cookie: _gh_sess=nnv%2B%2BlN4p7VFkGA5qIOTCAw%2Bth7OHRYw6jRDt9TGfTOBZPD5MFd11ZpSFzF7zBcagog2UzOr5beZEFi1CXDDcEuQjjapmwQMJ%2BLokkf8x5ryTypJU1v9bbHVcENsN7qry7G9OeZmYJHzBpCtlshFI9UsCZAMlp6nfmf6%2F7aNxCIRskRMbRZu16dmTdhr0Y8slpKzHtWxZQa8ZEht3Nq46h69GsJt7cGpX%2BvMd2PulTrXwuvy6LIwZyzS3Z%2Fg6kHAhW5ODpfFSeqt6JJQuwnmtA%3D%3D--6qVIdvrN9M2uBGpe--JlcbOGuiexjcZNJ4zVnv3A%3D%3D; Path=/; HttpOnly; Secure; SameSite=Lax
set-cookie: _octo=GH1.1.847927235.1767053723; Path=/; Domain=github.com; Expires=Wed, 30 Dec 2026 00:15:23 GMT; Secure; SameSite=Lax
set-cookie: logged_in=no; Path=/; Domain=github.com; Expires=Wed, 30 Dec 2026 00:15:23 GMT; HttpOnly; Secure; SameSite=Lax
x-github-request-id: B0A0:2C07D:691205E:7DD482B:6953199B
Examples · Cylix/cpp_redis Wiki · GitHub
Skip to content
Navigation Menu
{{ message }}
This repository was archived by the owner on Apr 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 561
Examples
Simon Ninon edited this page Nov 26, 2017
·
11 revisions
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <iostream>
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
int
main(void) {
#ifdef _WIN32
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0) {
std::cerr << "WSAStartup() failure" << std::endl;
return -1;
}
#endif /* _WIN32 */
//! Enable logging
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
cpp_redis::client client;
client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
if (status == cpp_redis::client::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
}
});
// same as client.send({ "SET", "hello", "42" }, ...)
client.set("hello", "42", [](cpp_redis::reply& reply) {
std::cout << "set hello 42: " << reply << std::endl;
// if (reply.is_string())
// do_something_with_string(reply.as_string())
});
// same as client.send({ "DECRBY", "hello", 12 }, ...)
client.decrby("hello", 12, [](cpp_redis::reply& reply) {
std::cout << "decrby hello 12: " << reply << std::endl;
// if (reply.is_integer())
// do_something_with_integer(reply.as_integer())
});
// same as client.send({ "GET", "hello" }, ...)
client.get("hello", [](cpp_redis::reply& reply) {
std::cout << "get hello: " << reply << std::endl;
// if (reply.is_string())
// do_something_with_string(reply.as_string())
});
// commands are pipelined and only sent when client.commit() is called
// client.commit();
// synchronous commit, no timeout
client.sync_commit();
// synchronous commit, timeout
// client.sync_commit(std::chrono::milliseconds(100));
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
return 0;
}// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <tacopie/tacopie>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <signal.h>
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
std::condition_variable should_exit;
void
sigint_handler(int) {
should_exit.notify_all();
}
int
main(void) {
#ifdef _WIN32
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0) {
std::cerr << "WSAStartup() failure" << std::endl;
return -1;
}
#endif /* _WIN32 */
//! Enable logging
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
cpp_redis::subscriber sub;
sub.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::subscriber::connect_state status) {
if (status == cpp_redis::subscriber::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
should_exit.notify_all();
}
});
//! authentication if server-server requires it
// sub.auth("some_password", [](const cpp_redis::reply& reply) {
// if (reply.is_error()) { std::cerr << "Authentication failed: " << reply.as_string() << std::endl; }
// else {
// std::cout << "successful authentication" << std::endl;
// }
// });
sub.subscribe("some_chan", [](const std::string& chan, const std::string& msg) {
std::cout << "MESSAGE " << chan << ": " << msg << std::endl;
});
sub.psubscribe("*", [](const std::string& chan, const std::string& msg) {
std::cout << "PMESSAGE " << chan << ": " << msg << std::endl;
});
sub.commit();
signal(SIGINT, &sigint_handler);
std::mutex mtx;
std::unique_lock<std::mutex> l(mtx);
should_exit.wait(l);
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
return 0;
}// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <iostream>
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
int
main(void) {
#ifdef _WIN32
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0) {
std::cerr << "WSAStartup() failure" << std::endl;
return -1;
}
#endif /* _WIN32 */
//! Enable logging
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
cpp_redis::client client;
client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
if (status == cpp_redis::client::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
}
});
//! Set a value
auto set = client.set("hello", "42");
auto decrby = client.decrby("hello", 12);
auto get = client.get("hello");
// commands are pipelined and only sent when client.commit() is called
// client.commit();
// synchronous commit, no timeout
client.sync_commit();
// synchronous commit, timeout
// client.sync_commit(std::chrono::milliseconds(100));
std::cout << "set 'hello' 42: " << set.get() << std::endl;
cpp_redis::reply r = decrby.get();
if (r.is_integer())
std::cout << "After 'hello' decrement by 12: " << r.as_integer() << std::endl;
std::cout << "get 'hello': " << get.get() << std::endl;
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
return 0;
}// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <iostream>
class my_logger : public cpp_redis::logger_iface {
public:
//! ctor & dtor
my_logger(void) = default;
~my_logger(void) = default;
//! copy ctor & assignment operator
my_logger(const my_logger&) = default;
my_logger& operator=(const my_logger&) = default;
public:
void
debug(const std::string& msg, const std::string& file, std::size_t line) {
std::cout << "debug: " << msg << " @ " << file << ":" << line << std::endl;
}
void
info(const std::string& msg, const std::string& file, std::size_t line) {
std::cout << "info: " << msg << " @ " << file << ":" << line << std::endl;
}
void
warn(const std::string& msg, const std::string& file, std::size_t line) {
std::cout << "warn: " << msg << " @ " << file << ":" << line << std::endl;
}
void
error(const std::string& msg, const std::string& file, std::size_t line) {
std::cerr << "error: " << msg << " @ " << file << ":" << line << std::endl;
}
};
int
main(void) {
//! By default, no logging
//! Force logger call, just for the example (you will never have to do that by yourself)
std::cout << "By default: no logging" << std::endl;
__CPP_REDIS_LOG(debug, "This is a debug message");
__CPP_REDIS_LOG(info, "This is an info message");
__CPP_REDIS_LOG(warn, "This is a warn message");
__CPP_REDIS_LOG(error, "This is an error message");
std::cout << std::endl;
//! Use the default logger, provided with the library
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
//! Force logger call, just for the example (you will never have to do that by yourself)
std::cout << "With the library provided logger" << std::endl;
__CPP_REDIS_LOG(debug, "This is a debug message");
__CPP_REDIS_LOG(info, "This is an info message");
__CPP_REDIS_LOG(warn, "This is a warn message");
__CPP_REDIS_LOG(error, "This is an error message");
std::cout << std::endl;
//! Use your custom logger
cpp_redis::active_logger = std::unique_ptr<my_logger>(new my_logger);
//! Force logger call, just for the example (you will never have to do that by yourself)
std::cout << "With an example of custom logger" << std::endl;
__CPP_REDIS_LOG(debug, "This is a debug message");
__CPP_REDIS_LOG(info, "This is an info message");
__CPP_REDIS_LOG(warn, "This is a warn message");
__CPP_REDIS_LOG(error, "This is an error message");
std::cout << std::endl;
return 0;
}
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <iostream>
#include <sstream>
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
int
main(void) {
#ifdef _WIN32
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0) {
std::cerr << "WSAStartup() failure" << std::endl;
return -1;
}
#endif /* _WIN32 */
cpp_redis::client client;
client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
if (status == cpp_redis::client::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
}
});
//! client kill ip:port
client.client_list([&client](cpp_redis::reply& reply) {
std::string addr;
std::stringstream ss(reply.as_string());
ss >> addr >> addr;
std::string host = std::string(addr.begin() + addr.find('=') + 1, addr.begin() + addr.find(':'));
int port = std::stoi(std::string(addr.begin() + addr.find(':') + 1, addr.end()));
client.client_kill(host, port, [](cpp_redis::reply& reply) {
std::cout << reply << std::endl; //! OK
});
client.commit();
});
client.sync_commit();
std::this_thread::sleep_for(std::chrono::seconds(1));
if (!client.is_connected()) {
client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
if (status == cpp_redis::client::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
}
});
}
//! client kill filter
client.client_list([&client](cpp_redis::reply& reply) {
std::string id_str;
std::stringstream ss(reply.as_string());
ss >> id_str;
uint64_t id = std::stoi(std::string(id_str.begin() + id_str.find('=') + 1, id_str.end()));
client.client_kill(id, false, cpp_redis::client::client_type::normal, [](cpp_redis::reply& reply) {
std::cout << reply << std::endl; //! 1
});
client.commit();
});
client.sync_commit();
std::this_thread::sleep_for(std::chrono::seconds(1));
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
return 0;
}// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <cpp_redis/cpp_redis>
#include <iostream>
#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
int
main(void) {
#ifdef _WIN32
//! Windows netword DLL init
WORD version = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(version, &data) != 0) {
std::cerr << "WSAStartup() failure" << std::endl;
return -1;
}
#endif /* _WIN32 */
//! Enable logging
cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
//! High availablity requires at least 2 io service workers
cpp_redis::network::set_default_nb_workers(2);
cpp_redis::client client;
//! Add your sentinels by IP/Host & Port
client.add_sentinel("127.0.0.1", 26379);
//! Call connect with optional timeout
//! Can put a loop around this until is_connected() returns true.
client.connect("mymaster", [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
if (status == cpp_redis::client::connect_state::dropped) {
std::cout << "client disconnected from " << host << ":" << port << std::endl;
}
},
0, -1, 5000);
// same as client.send({ "SET", "hello", "42" }, ...)
client.set("hello", "42", [](cpp_redis::reply& reply) {
std::cout << "set hello 42: " << reply << std::endl;
// if (reply.is_string())
// do_something_with_string(reply.as_string())
});
while (true) {
// same as client.send({ "DECRBY", "hello", 12 }, ...)
client.incrby("hello", 12, [](cpp_redis::reply& reply) {
std::cout << "incrby hello 12: " << reply << std::endl;
// if (reply.is_integer())
// do_something_with_integer(reply.as_integer())
});
// same as client.send({ "GET", "hello" }, ...)
client.get("hello", [](cpp_redis::reply& reply) {
std::cout << "get hello: " << reply << std::endl;
// if (reply.is_string())
// do_something_with_string(reply.as_string())
});
// commands are pipelined and only sent when client.commit() is called
// client.commit();
// synchronous commit, no timeout
client.sync_commit();
std::cout << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}
#ifdef _WIN32
WSACleanup();
#endif /* _WIN32 */
return 0;
}This example is based on a sentinel using the the following default sentinel configuration file:
# Example sentinel.conf
# *** IMPORTANT ***
#
# By default Sentinel will not be reachable from interfaces different than
# localhost, either use the 'bind' directive to bind to a list of network
# interfaces, or disable protected mode with "protected-mode no" by
# adding it to this configuration file.
#
# Before doing that MAKE SURE the instance is protected from the outside
# world via firewalling or other means.
#
# For example you may use one of the following:
#
# bind 127.0.0.1 192.168.1.1
#
# protected-mode no
# port <sentinel-port>
# The port that this sentinel instance will run on
port 26379
# sentinel announce-ip <ip>
# sentinel announce-port <port>
#
# The above two configuration directives are useful in environments where,
# because of NAT, Sentinel is reachable from outside via a non-local address.
#
# When announce-ip is provided, the Sentinel will claim the specified IP address
# in HELLO messages used to gossip its presence, instead of auto-detecting the
# local address as it usually does.
#
# Similarly when announce-port is provided and is valid and non-zero, Sentinel
# will announce the specified TCP port.
#
# The two options don't need to be used together, if only announce-ip is
# provided, the Sentinel will announce the specified IP and the server port
# as specified by the "port" option. If only announce-port is provided, the
# Sentinel will announce the auto-detected local IP and the specified port.
#
# Example:
#
# sentinel announce-ip 1.2.3.4
# dir <working-directory>
# Every long running process should have a well-defined working directory.
# For Redis Sentinel to chdir to /tmp at startup is the simplest thing
# for the process to don't interfere with administrative tasks such as
# unmounting filesystems.
dir /tmp
# sentinel monitor <master-name> <ip> <redis-port> <quorum>
#
# Tells Sentinel to monitor this master, and to consider it in O_DOWN
# (Objectively Down) state only if at least <quorum> sentinels agree.
#
# Note that whatever is the ODOWN quorum, a Sentinel will require to
# be elected by the majority of the known Sentinels in order to
# start a failover, so no failover can be performed in minority.
#
# Slaves are auto-discovered, so you don't need to specify slaves in
# any way. Sentinel itself will rewrite this configuration file adding
# the slaves using additional configuration options.
# Also note that the configuration file is rewritten when a
# slave is promoted to master.
#
# Note: master name should not include special characters or spaces.
# The valid charset is A-z 0-9 and the three characters ".-_".
sentinel monitor mymaster 127.0.0.1 6379 2
# sentinel auth-pass <master-name> <password>
#
# Set the password to use to authenticate with the master and slaves.
# Useful if there is a password set in the Redis instances to monitor.
#
# Note that the master password is also used for slaves, so it is not
# possible to set a different password in masters and slaves instances
# if you want to be able to monitor these instances with Sentinel.
#
# However you can have Redis instances without the authentication enabled
# mixed with Redis instances requiring the authentication (as long as the
# password set is the same for all the instances requiring the password) as
# the AUTH command will have no effect in Redis instances with authentication
# switched off.
#
# Example:
#
# sentinel auth-pass mymaster MySUPER--secret-0123passw0rd
# sentinel down-after-milliseconds <master-name> <milliseconds>
#
# Number of milliseconds the master (or any attached slave or sentinel) should
# be unreachable (as in, not acceptable reply to PING, continuously, for the
# specified period) in order to consider it in S_DOWN state (Subjectively
# Down).
#
# Default is 30 seconds.
sentinel down-after-milliseconds mymaster 30000
# sentinel parallel-syncs <master-name> <numslaves>
#
# How many slaves we can reconfigure to point to the new slave simultaneously
# during the failover. Use a low number if you use the slaves to serve query
# to avoid that all the slaves will be unreachable at about the same
# time while performing the synchronization with the master.
sentinel parallel-syncs mymaster 1
# sentinel failover-timeout <master-name> <milliseconds>
#
# Specifies the failover timeout in milliseconds. It is used in many ways:
#
# - The time needed to re-start a failover after a previous failover was
# already tried against the same master by a given Sentinel, is two
# times the failover timeout.
#
# - The time needed for a slave replicating to a wrong master according
# to a Sentinel current configuration, to be forced to replicate
# with the right master, is exactly the failover timeout (counting since
# the moment a Sentinel detected the misconfiguration).
#
# - The time needed to cancel a failover that is already in progress but
# did not produced any configuration change (SLAVEOF NO ONE yet not
# acknowledged by the promoted slave).
#
# - The maximum time a failover in progress waits for all the slaves to be
# reconfigured as slaves of the new master. However even after this time
# the slaves will be reconfigured by the Sentinels anyway, but not with
# the exact parallel-syncs progression as specified.
#
# Default is 3 minutes.
sentinel failover-timeout mymaster 180000
# SCRIPTS EXECUTION
#
# sentinel notification-script and sentinel reconfig-script are used in order
# to configure scripts that are called to notify the system administrator
# or to reconfigure clients after a failover. The scripts are executed
# with the following rules for error handling:
#
# If script exits with "1" the execution is retried later (up to a maximum
# number of times currently set to 10).
#
# If script exits with "2" (or an higher value) the script execution is
# not retried.
#
# If script terminates because it receives a signal the behavior is the same
# as exit code 1.
#
# A script has a maximum running time of 60 seconds. After this limit is
# reached the script is terminated with a SIGKILL and the execution retried.
# NOTIFICATION SCRIPT
#
# sentinel notification-script <master-name> <script-path>
#
# Call the specified notification script for any sentinel event that is
# generated in the WARNING level (for instance -sdown, -odown, and so forth).
# This script should notify the system administrator via email, SMS, or any
# other messaging system, that there is something wrong with the monitored
# Redis systems.
#
# The script is called with just two arguments: the first is the event type
# and the second the event description.
#
# The script must exist and be executable in order for sentinel to start if
# this option is provided.
#
# Example:
#
# sentinel notification-script mymaster /var/redis/notify.sh
# CLIENTS RECONFIGURATION SCRIPT
#
# sentinel client-reconfig-script <master-name> <script-path>
#
# When the master changed because of a failover a script can be called in
# order to perform application-specific tasks to notify the clients that the
# configuration has changed and the master is at a different address.
#
# The following arguments are passed to the script:
#
# <master-name> <role> <state> <from-ip> <from-port> <to-ip> <to-port>
#
# <state> is currently always "failover"
# <role> is either "leader" or "observer"
#
# The arguments from-ip, from-port, to-ip, to-port are used to communicate
# the old address of the master and the new address of the elected slave
# (now a master).
#
# This script should be resistant to multiple invocations.
#
# Example:
#
# sentinel client-reconfig-script mymaster /var/redis/reconfig.sh
Need more information? Contact me.
Clone this wiki locally
You can’t perform that action at this time.