mirror of
https://github.com/boostorg/redis.git
synced 2026-01-19 04:42:09 +00:00
81 lines
2.0 KiB
C++
81 lines
2.0 KiB
C++
/* Copyright (c) 2018-2022 Marcelo Zimbres Silva (mzimbres@gmail.com)
|
|
*
|
|
* Distributed under the Boost Software License, Version 1.0. (See
|
|
* accompanying file LICENSE.txt)
|
|
*/
|
|
|
|
#include <tuple>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <iostream>
|
|
#include <boost/asio.hpp>
|
|
#include <boost/redis.hpp>
|
|
|
|
// Include this in no more than one .cpp file.
|
|
#include <boost/redis/src.hpp>
|
|
|
|
namespace net = boost::asio;
|
|
namespace redis = boost::redis;
|
|
using connection = redis::connection;
|
|
using boost::redis::request;
|
|
using boost::redis::response;
|
|
|
|
template <class Response>
|
|
auto exec(std::shared_ptr<connection> conn, request const& req, Response& resp)
|
|
{
|
|
net::dispatch(
|
|
conn->get_executor(),
|
|
net::deferred([&]() { return conn->async_exec(req, resp, net::deferred); }))
|
|
(net::use_future).get();
|
|
}
|
|
|
|
auto logger = [](auto const& ec)
|
|
{ std::clog << "Run: " << ec.message() << std::endl; };
|
|
|
|
auto main(int argc, char * argv[]) -> int
|
|
{
|
|
try {
|
|
std::string host = "127.0.0.1";
|
|
std::string port = "6379";
|
|
|
|
if (argc == 3) {
|
|
host = argv[1];
|
|
port = argv[2];
|
|
}
|
|
|
|
net::io_context ioc{1};
|
|
|
|
auto conn = std::make_shared<connection>(ioc);
|
|
|
|
// Resolves the address
|
|
net::ip::tcp::resolver resv{ioc};
|
|
auto const res = resv.resolve(host, port);
|
|
|
|
// Connect to Redis
|
|
net::connect(conn->next_layer(), res);
|
|
|
|
// Starts a thread that will can io_context::run on which
|
|
// the connection will run.
|
|
std::thread t{[conn, &ioc]() {
|
|
conn->async_run(logger);
|
|
ioc.run();
|
|
}};
|
|
|
|
request req;
|
|
req.push("HELLO", 3);
|
|
req.push("PING");
|
|
req.push("QUIT");
|
|
|
|
response<boost::redis::ignore_t, std::string, boost::redis::ignore_t> resp;
|
|
|
|
// Executes commands synchronously.
|
|
exec(conn, req, resp);
|
|
|
|
std::cout << "Response: " << std::get<1>(resp) << std::endl;
|
|
|
|
t.join();
|
|
} catch (std::exception const& e) {
|
|
std::cerr << e.what() << std::endl;
|
|
}
|
|
}
|